Nested loops 
 
The term nested loop means simply “loops inside of loops”. To better understand 
how nested loops work, let’s have a look at a very short, simple representative 
program. 
 
/* nested loops example */ 
/* #include <stdio.h> */ 
main(){ 
 float a[3][3]; 
 int i,j; 
 for (i=0; i<3; i++) 
  for (j=0; j<3; j++) 
   scanf(“%f”,&a[i][j]); 
} 
 
The program uses a pair of “for” loops to read values from the keyboard and assign 
them to a 3x3 2-dimensional array a[3][3]. Remember that such an array looks 
something like the following: 
a[0][0]  a[0][1]  a[0][2] 
a[1][0]  a[1][1]  a[1][2] 
a[2][0]  a[2][1]  a[2][2] 
 
Considering just the loop counter (i and j) values, the above program executes as 
follows: 
 
 
This means that values entered from the keyboard are read into “%f” by scanf() and 
assigned to array a[3][3] in sequence by “&a[i][j] as “i” and “j” change values as noted 
above.  
Let’s expand on this program so that a second nested loop reads the values out of 
the array and displays them on the screen. 
 
/* nested loops example 2 */ 
/* #include <stdio.h> */ 
main(){ 
 float a[3][3]; 
 int i,j; 
 for (i=0; i<3; i++) 
  for (j=0; j<3; j++) 
   scanf(“%f”,&a[i][j]); 
 for (i=0; i<3; i++) { 
  for (j=0; j<3; j++) 
   printf(“%8.2f”,a[i][j]); 
  printf(“¥n”); 
 } 
}