EXAMPLE
This
is an example of a simple nested FOR loop program. It is done in two parts to show you how
it is built up.
PART 1
First,
create the program that uses a loop to output the numbers 1 to 15 on a
single.
SOLUTION
for(int n=1; n<=15; n++)
{
System.out.print(n
+ ",");
}
System.out.println("");
The above code will output:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
Note that
the 2nd println
statement is simply there to bring the cursor to the next line.
PART 2
Write
the program that will output numbers 1 to 15 on the same line and do that 5
different times.
PSEUDOCODE SOLUTION
Loop five times
{
Output numbers
from 1 to 15 on same line
}
The "loop five times" is a simple for loop. And the "output numbers" line
that is inside the loop is the solution from part 1. Putting this all together, we get:
for (int c=0; c<5; c++)
{
for(int n=1; n<=15; n++)
{
System.out.print(n
+ ",");
}
System.out.println("");
}
The above will output:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
|