A nested loop means a loop within a loop.
Or we can say an inner loop within the body of an outer loop.
A Clock is a fine example of nested loop where HOUR hand and MINUTE
hand all spin around the face of the clock.
The HOUR hand is like outer loop and MINUTE hand is like inner loop.
The HOUR hand only makes one revolution for every 60 of the MINUTE
hand’s revolution.(i.e. MINUTE hand increment it value by 1 ).
In case of pattern programs outer loop used for generating ROWS and inner
loop is used for generating COLUMNS for particular ROWS.
We can use it in patterns, 2D arrays and it just like GRID or table.
public class DemoNestedLoop { public static void main(String[] args) { for(int outer = 1;outer <=3 ; outer++) { for(int inner = 1; inner <=3 ; inner++) { System.out.println("outer :: "+outer +"\tinner ::"+inner); } System.out.println(); } for(int i = 0;i <= 5; i++) { for(int j = 0;j < i; j++) { System.out.print(" "+j); } System.out.println(); } } }
0 comments:
Post a Comment