- What a nested while loop is and why we use it in C programming
- How the nested while loop works with real examples
- Where to use nested while loops in real applications
- How to write a program using nested while loop
- Complete program examples with explanations
Introduction
In this tutorial section, we will understand what a nested while loop is in the C Language and how it works with real-world examples.
What is a Nested while Loop in C?
A nested while loop in C means having one while loop placed inside another. In simple words, it's a loop within a loop. You can nest any number of loops based on your logic. C Programming fully supports this structure, and it's often used in complex tasks that need repeated checking or processing of conditions.
Usually, the outer while loop starts first. Then, the inner while loop runs completely for each iteration of the outer loop. The inner loop keeps executing as long as its condition is true. Once it finishes, control returns to the outer loop for the next round. This keeps repeating until the outer loop condition becomes false.
💡 Key Point: In a nested while loop, the inner loop completes all its iterations for each single iteration of the outer loop.
Real-World Use Cases of Nested while Loops
Here are some everyday situations where nested while loops apply:
- Unlocking a mobile phone: With up to 3 password attempts, nested loops can handle multiple attempts.
- Spell checking: In software like Microsoft Word, nested loops check each word against a dictionary.
- Username and password validation: Validating both until both are correct.
- OTP validation: One-Time Password input and validation within a limited number of tries.
- Multiplication tables: Printing tables from 1 to 10 using row-column format.
Advantages of Using Nested while Loop in C Programming
1. Improves CPU efficiency — When structured properly for repetitive tasks
2. Processes multi-dimensional data — Matrices, grids, and tables
3. Handles complex logic — Where one loop depends on another, like user credential validation
4. Great for table-based outputs — Multiplication tables, row-column style execution
5. Better control — Over layered or step-wise data processing
Disadvantages of Using Nested while Loop in C Programming
1. Performance overhead: If the nested data is large, nested while loops can consume more memory and CPU time.
2. Harder to debug: Nested loops are harder to understand and debug, especially for beginners.
3. Less efficient: When data is not well-structured, nested loops can make code less efficient.
4. Infinite loop risk: Improper nesting or missing loop conditions may lead to infinite loops.
5. Reduced readability: Overuse of nested loops can make code harder to modify or extend.
Flowchart of Nested while Loop
The flowchart below shows how the nested while loop works step by step:
Step-by-step explanation:
Initially, the outer while loop evaluates the test expression. If the condition is false, the flow of control skips the loop and comes out of the outer loop. If the condition is true, the control enters the inner while loop.
Inside the inner loop, the test expression is again evaluated. If it's true, the statements inside the inner loop are executed. If the condition is false, the control skips the inner loop and jumps to the outer loop's update expression.
After executing the outer loop's statement, the control goes back to the outer while condition and rechecks it. This process continues as long as the condition remains true.
Syntax of Nested while Loop in C
Let us first look at a real-world example of the syntax for a nested while loop in C and then we will go into detail about each part of it.
/* statements outside loop */
/* initialization */
int i = 1, j = 1;
while (outer_condition) {
/* Outer while statements */
while (inner_condition) {
/* Inner while statements */
j++;
}
/* Outer while statements */
i++;
}
/* statement outside loop */
Let's break down each part:
🔹 Outer while loop: The program starts by entering the outer while loop. It checks the condition written in the outer while loop. If the condition is false, the program skips the loop entirely.
🔹 Inner while loop: If the outer condition is true, the program enters the inner while loop. The inner loop condition is checked. If true, it runs the statements inside the inner while loop.
🔹 Loop body: The statements inside the inner loop execute repeatedly until the inner condition becomes false.
🔹 Repeating process: Once the inner loop ends, control returns to the outer loop and the whole process repeats.
⚠️ Important: In a nested while loop, the inner loop must have its own initialization, condition, and update expression to avoid infinite loops.
C Program to Illustrate Nested while Loop
The program below displays the multiplication table from 1 to 10 using nested while loops.
#include <stdio.h>
int main() {
int n = 1, i = 1;
printf("\n Table from 1...10 Using Nested While loop\n");
while (n <= 10) {
i = 1;
while (i <= 10) {
printf("\t %d", n * i);
i++;
}
n++;
printf("\n");
}
return 0;
}
Sample Output:
Table from 1...10 Using Nested While loop 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100
Explanation:
- The variables
int n = 1, i = 1;are declared and initialized. - The line
printf("\n Table from 1...10 Using Nested While loop");displays the heading message. - The program enters the outer loop
while(n <= 10). Sincen = 1, the condition is true. - Inside the outer loop,
iis re-initialized to 1. - The program enters the inner loop
while(i <= 10). Sincei = 1, the condition is true. - It executes
printf("\t %d", n * i);which prints the product — in this case, 1 × 1 = 1. - Then
i++increases the value ofito 2. - The condition
i <= 10is checked again, and since it's still true, the loop continues. - This continues until
ibecomes 11, which makes the condition false. - The inner loop ends, and control returns to the outer loop. Then
n++increases the value ofnto 2. - The outer loop checks
n <= 10again, and since it's true, it goes through the same process. - This continues until
nbecomes 11, which breaks the outer loop. - As a result, we get the full multiplication table from 1 to 10 printed using nested while loops.
💻 Practice Exercise
Challenge: Write a program that prints a pattern of asterisks (*) in the shape of a right triangle using nested while loops. The program should ask the user for the number of rows.
🔍 Click to Show Solution
#include <stdio.h>
int main() {
int rows, i = 1, j;
printf("Enter number of rows: ");
scanf("%d", &rows);
while (i <= rows) {
j = 1;
while (j <= i) {
printf("* ");
j++;
}
printf("\n");
i++;
}
return 0;
}
/* Sample Output for rows = 5:
*
* *
* * *
* * * *
* * * * * */
📝 Summary
- A nested while loop is a loop within another loop
- The inner loop completes all its iterations for each outer loop iteration
- It is useful for processing multi-dimensional data like matrices and tables
- Common real-world uses include: multiplication tables, pattern printing, and validation systems
- Proper initialization, update expressions, and loop conditions are necessary to avoid infinite loops
Frequently Asked Questions About Nested while Loop in C
1. What is a nested while loop in C?
A nested while loop is a while loop placed inside another while loop. The inner loop executes completely for each iteration of the outer loop.
2. When should I use a nested while loop?
Use nested while loops when you need to process data in multiple dimensions, such as matrices, tables, or when one loop's execution depends on another loop's iterations.
3. Can I nest more than two while loops?
Yes, you can nest as many while loops as needed. However, too many nested loops can make code hard to read and debug.
4. What happens if the inner loop condition is never false?
If the inner loop condition is never false, it creates an infinite loop. This will cause the program to run forever and may crash your system.
5. What is the difference between nested while and nested for loop?
The main difference is syntax. While loops are used when the number of iterations is unknown, and for loops are used when the number of iterations is known. However, both can be nested and achieve similar results.
💡 Tip: When writing nested while loops, always make sure the inner loop's update expression eventually makes the condition false. Otherwise, you might create an infinite loop.