Do-While Loop Counting 1 to 30 on separate lines in Java

Viewed 3231

I am currently in a java class learning about all types of loops, and am stuck on a question specifically on do-while loops. The question asks that we create a do-while loop that counts 1 to 30, with the counting jumping to the next line after 10 integers, for example:

1 2 3 4 5 6 7 8 9 10

11 12 13 14 15 16 17 18 19 20

21 22 23 24 25 26 27 28 29 30

I have my loop started, and I can have it print values one through thirty, but I am not sure how to make it skip a line every 10 integers. Here is my current code:

int q = 0;
do
{       
    q=q+1;
    System.out.print(q+" ");
}
while (q<30);
System.out.println();
3 Answers

Add this line to your code and it will work.

if (q % 10 == 0) System.out.println();

if q is divisible by 10, then you write a line to the system out.

Place it after the line System.out.print(q+" ");

    int q = 0;
do
{       
    q=q+1;
    System.out.print(q+" ");

    if(q% 10==0)   {
        System.out.println();
    }
       }
while (q<30);

Here is an example as to how you can get the line to skip every 10 integers:

public class App 
               {
        public static void main( String[] args )throws IOException{
              int y = 1;
              int x = 0;
              do {
                  System.out.print(y + " ");
                  x++;
                  y++;
                  if(x >= 10) {
                           System.out.println();
                           x = 0;
                  }
               }while(y <= 30);

   }



}

What we can do is create a "control" variable (x). We can increment it each time during the loop. When x is >= 10, we can print a blank line. We will print each time through while our y variable is <= 30. Here is the output of the program:

1 2 3 4 5 6 7 8 9 10 
11 12 13 14 15 16 17 18 19 20 
21 22 23 24 25 26 27 28 29 30 
Related