Nested Loop
Nested Loop
(Nested Loop)
CSE 1111: Structured Programming Language
Charles Aunkan Gomes
Lecturer
Dept of CSE, UIU
1
Nested Loop
Just like nested if else C allows the looping of statements inside another loop
There is no restriction for defining any number of loops. The nesting level
can be defined at n times.
Example :
Outer_loop {
//outer loop statements…
Inner_loop {
// inner loop statements.
}
// outer loop statements.
}
Nested for loop Syntax
for(initialization; condition; update loop variable) {
// statement 1
………………………….
do {
// Inner loop statements
}while(condition);
// statements
}while(condition);
Nested for loop Syntax
for(outVariable initialization ; condition; update outVariable) {
// statement 1
………………………….
outer
loop
*********
}
How can we solve?
Outer loop indicates/defines the row
Where should we put the "\n”?
Inner loop indicated/defines the column
Nested for loop Example
Sample Output
for(i=1 ; i<=3 ; i++){
***
for(j=1 ; j<=3; j++){ ***
printf(“*”); ***
}
printf(“\n”);
}
Outer loop indicates/defines the row
Inner loop indicated/defines the column
Nested for loop Example Code
for(i=1; i<=2; i++) { Outer loop Inner loop
for(j=1; j<=2; j++) { Value of i condition Execution Value of j condition Execution
printf(“i:%d, j:%d\n”,i,j);
;1 1<=2, True Execute inner loop 1 1<=2,true i:1,j:1
} 2 2<=2,true i:1,j:2
3 3<=2,false
} 2 2<=2,True Execute inner loop 1 1<=2,true i:2,j:1
2 2<=2,true i:2,j:2
3 3<=2,false
3 3<=2,False
Nested for loop Example (printing pattern)
Take input of a number n and print a pattern
for(i=1 ; i<=n ; i++){ Intput: n=3
Sample Output
for(j=1 ; j<=i; j++){ 1
12
printf(“%d”,j); 123
} Input: n=4
printf(“\n”); Sample output
1
} 12
123
1234
1 2 3 2 1 1
1 2 1 2 3
2 4 5 6
1
1 2 1
1 2 3 2 1