Home > Software design >  Write a while loop that prints all positive numbers that are divisible by 10 and less than a given n
Write a while loop that prints all positive numbers that are divisible by 10 and less than a given n

Time:10-07

I have this homework problem and I cannot seem to get it at all. the suggested outcome if n were to be 100 would be 10 20 30 40 50 60 70 80 90

I know my question is probably really stupid but I cannot seem to understand this for the life of me.

Scanner in = new Scanner(System.in);
      System.out.print("n: ");
      int n = in.nextInt();
      
      while (n % 10 < 1)
      {
         System.out.print(n   " ");
         n = n - 1;
      }
      System.out.println(); 

CodePudding user response:

I guess you were trying to make the program without using an extra variable, but you have to take an extra variable if you want all the numbers to be displayed in increasing order. You can try this code snippet out. It will work.

  Scanner in = new Scanner(System.in);
  System.out.print("n: ");
  int n = in.nextInt();
  int a = 10;
  while(a <= n){
    System.out.print(a " ");
    a  = 10;
  }

CodePudding user response:

There are many solutions, you can do it with help of an extra variable.

Scanner in = new Scanner(System.in);
System.out.print("n: ");
int n = in.nextInt();
int iter = 10;
while(iter < n)
{
    System.out.print(iter   " ");
    iter  = 10;
}
  •  Tags:  
  • java
  • Related