The method evenSquares
takes a single int parameter, n, (for example, 10000), and then prints all of the (positive) even perfect squares less than n, each on a separate line.
Notice that evenSquares has a void return type, since all it does is print integers to the console. Be sure to use the println
method to print each entry of your output.
Example: if n = 40, your code should print:
4
16
36
(Hint: your method should be built around a for loop with a test component that asks if the square of the control variable (say, k) is < n. Thus, the loop should terminate as soon as k*k equals or exceeds n.)
I'm given this
public void evenSquares(int n) {
public class Squares {
public static void main(String[] args) {
evenSquares(40);
}
public static void evenSquares(int n) {
for(int sq, k=2; (sq = k*k) <= n ; k += 2){
System.out.println(sq);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.