EasyManua.ls Logo

Casio Z-1

Casio Z-1
126 pages
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
98
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:
First pass (i)
Second pass (i)
Third pass (i)
i=0
j=0
j=1
j=2
i=1
j=0
j=1
j=2
i=2
j=0
j=1
j=2
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”);
}
}

Table of Contents

Related product manuals