Nested while Loop in C Programming
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Nested while Loop in C Programming – Complete Guide for Beginners

📑 On this page:
  • Introduction
  • What is a Nested while Loop?
  • Real-World Use Cases
  • Advantages of Nested while Loop
  • Disadvantages of Nested while Loop
  • Flowchart of Nested while Loop
  • Syntax of Nested while Loop
  • Program Example - Multiplication Table
  • Frequently Asked Questions
📚 In this tutorial, you will learn:
  • 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:

Flowchart of nested while loop in C language showing execution flow

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.

Nested while loop syntax in C Programming

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:

  1. The variables int n = 1, i = 1; are declared and initialized.
  2. The line printf("\n Table from 1...10 Using Nested While loop"); displays the heading message.
  3. The program enters the outer loop while(n <= 10). Since n = 1, the condition is true.
  4. Inside the outer loop, i is re-initialized to 1.
  5. The program enters the inner loop while(i <= 10). Since i = 1, the condition is true.
  6. It executes printf("\t %d", n * i); which prints the product — in this case, 1 × 1 = 1.
  7. Then i++ increases the value of i to 2.
  8. The condition i <= 10 is checked again, and since it's still true, the loop continues.
  9. This continues until i becomes 11, which makes the condition false.
  10. The inner loop ends, and control returns to the outer loop. Then n++ increases the value of n to 2.
  11. The outer loop checks n <= 10 again, and since it's true, it goes through the same process.
  12. This continues until n becomes 11, which breaks the outer loop.
  13. 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.

📖 Related Tutorials

  • while Loop in C - Complete Guide
  • do-while Loop in C - Complete Guide
  • for Loop in C - Complete Guide
  • Introduction to Loops in C

Previous Topic: -->> while loop in C   ||   Next topic: -->> Difference between while and do-while loop


📚 Explore More Topics

🗄️ SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

🐍 Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

☕ Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.