(Lesson 5) Nested Loops
(Lesson 5) Nested Loops
A loop can contain any kind of statement(s) inside its body, including
another loop. One loop inside another is called a nested loop.
The counter variable of the inner loop should have a different name,
so that it will not conflict with the outer loop.
A nested loop has the following syntax, as an example:
In this example, the inner loop is
repeated 5 times for each of the10
rounds of the outer loop.
Example (1): A Simple Pattern
How about asking the user to enter the number of rows and the
number of columns for the pattern…
Output Console
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
Example (2): More interaction (input)
import javax.swing.*;
public class Prog2
{
public static void main(String[] args)
{
int x = Integer.parseInt(JOptionPane.showInputDialog("Enter the numnber of rows:"));
int y = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of columns:"));
for (int r=1; r<=x; r++)
{
for (int c=1; c<=y; c++)
System.out.print(" * ");
System.out.println();
}
}
}
Can you display
the output in a
message box?
Try it ☺
Example (3): Switching (X and O)
In this example, if the column index is even, the program will print an
“X” letter. If it is odd, it will print an “O”.
for (int r=1; r<=4; r++)
{
for (int c=1; c<=6; c++) Output Console
{
if(c%2==0) O X O X O X
Prog3.java
System.out.print(" X "); O X O X O X
else O X O X O X
System.out.print(" O "); O X O X O X
}
System.out.println();
}
Example (4): A changing number of columns
In this example, the number of columns is different at each row (i.e. you don’t
have a fixed number of columns at each row). So, on the 1st row you need to
make one column, at the 2nd row you need two columns, and so on.
Prog4.java Output Console
for (int r=1; r<=6; r++) X
{ X X
for (int c=1; c<=r; c++) X X X
System.out.print(" X ");
X X X X
System.out.println();
X X X X X
} X X X X X X
Now, let’s work a little bit with numbers!
Nested Loops: More examples
The user is asked to enter the number of rows and columns, and
accordingly the program prints the times table of those numbers.
Output Console
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
Example (7): Multiplication Table
import javax.swing.*;
public class Prog7
{
public static void main(String[] args)
{
int x = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of rows: "));
int y = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of columns:"));
for (int r=1; r<=x; r++)
{
for (int c=1; c<=y; c++)
System.out.print(r*c + "\t");
System.out.println();
}
}
}