The while and do-while loops Squares of natural numbers

Read an integer number N from the input and print all the squares of natural numbers:

  • less than or equal to N,
  • in ascending order.

Sample Input 1:

50

Sample Output 1:

1
4
9
16
25
36
49

Sample Input 2:

1

Sample Output 2:

1

Solution

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        final int maximum = new Scanner(System.in).nextInt();

        int counter = 1;
        int square;

        while ((square = counter * counter++) <= maximum) {
            System.out.println(square);
        }
    }
}

可以利用while中条件判断语句进行赋值以及++/--运算,因为条件判断语句一定会执行,所以这里要注意语句中的赋值以及进行其他计算的结果。

posted @ 2020-08-11 14:35  longlong6296  阅读(76)  评论(0)    收藏  举报