Nested for loop



A loop inside another loop is called the nesting of loops. So a for loop inside the body of another for loop is called a nested for loop. Nesting of for loop are essential for handling multidimensional arrays. Also nested for loop are needed for handling table of contents (rows & columns).  

 Syntax of a Nested for loop:
  
                                                        for ( initialization ; condition ; updating)
                                                        { // Starting of outer loop
                                                       
                                                       for ( initialization ; condition ; updating)
                                                        { // Starting of inner loop
                                                         Statement / Statements ;                                                   
                                                        }
                                                         Statement / Statements ;        

                                                        }

Nested for loop example:

  1. class NestedDemo
  2. {
  3. public static void main(String args[])
  4. {
  5. for(int i = 0 ;i<10; i++ ) // outer loop
  6. {
  7. for(int j = 1; j<=i+1; j++ )// inner loop
  8. {
  9. System.out.print("*");
  10. }
  11. System.out.println();
  12. }
  13. }
  14. }