Nested while Loops in C Programming Language
The way if statements can be nested, similarly while and for can also be nested. To understand how nested loops work, look at the program given below:
The way if statements can be nested, similarly while and for can also be nested. To understand how nested loops work, look at the program given below:
#include <stdio.h>
void main()
{
int i = 1;
int j = 1;
while(i<=3){
while(j<=3){
printf("Welcome ");
j++;
}
printf("\n");
j = 1;
i++;
}
}
Welcome Welcome Welcome
Welcome Welcome Welcome
Welcome Welcome Welcome
Press any key to continue . . .
This C program uses nested while loops to print the word "Welcome" multiple times in a row and column pattern.
#include
void main()
{
int i = 1;
int j = 1;
while(i <= 3)
{
while(j <= 3)
{
printf("Welcome ");
j++;
}
printf("\n");
j = 1;
i++;
}
}
int i = 1;
int j = 1;
while(i <= 3)
The outer loop executes 3 times because the value of i starts from 1 and continues until 3. Each iteration of the outer loop represents one row.
while(j <= 3)
{
printf("Welcome ");
j++;
}
The inner loop prints the word "Welcome" three times in a single row. After each print operation, the value of j is increased by 1.
| Value of j | Output |
|---|---|
| 1 | Welcome |
| 2 | Welcome |
| 3 | Welcome |
When j becomes 4, the condition j <= 3 becomes false and the inner loop terminates.
printf("\n");
This statement moves the cursor to the next line after printing three "Welcome" words.
j = 1;
The value of j is reset to 1 so that the inner loop can execute again for the next row. Without this statement, the inner loop would not run again because j would already be greater than 3.
i++;
The value of i is increased by 1 to move to the next row.
First Iteration (i = 1)
Welcome Welcome Welcome
Second Iteration (i = 2)
Welcome Welcome Welcome
Third Iteration (i = 3)
Welcome Welcome Welcome
Welcome Welcome Welcome
Welcome Welcome Welcome
Welcome Welcome Welcome
This program demonstrates the use of nested while loops in C. The outer loop creates three rows, while the inner loop prints the word "Welcome" three times in each row, producing a 3 × 3 pattern.
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.