Mastering the While Loop in C: A Complete Guide to Logic & Flowcharts

Table of Contents

C while Loops

The while loop in C is one of the most fundamental and powerful looping constructs in programming. It allows you to execute a block of code repeatedly as long as a condition remains true. A while loop is an entry-controlled loop, meaning the condition is checked before the loop body executes.

Syntax of While Loop in C

 
while (condition)
{
  // statements
}
Flowchart diagram of a C while loop: The flow starts at initialization, enters a decision diamond to check a condition, loops back if True and exits if False.
The Entry-Control Loop: Notice how the condition is checked at the very top. If the condition is false initially, the code block is never executed.

Key Points:

• The condition must evaluate to true (non-zero) or false (zero)

• The loop body runs only if the condition is True.

• Condition is checked before each iteration

 

Consider an example below: Write a C Program to print numbers from 1 to 5 using while loop

				
					#include <stdio.h>
int main()
{
    int i = 1;
    while (i <= 5)
    {
        <mark id="p_6">printf("%d\n", i);
        i++;
    }
    return 0;
}

// 1
// 2
// 3
// 4
// 5
				
			
value of i(i <= 5)OutputNew Value (i++)
1True12
2True23
3True34
4True45
5True56
6FalseLoop Stops-

Write a C program to for the Fibonacci Series by using while loop

				
					#include <stdio.h>
int main() {
    int n = 10, first = 0, second = 1, next, i = 1;
    printf("Fibonacci Series: ");
    while (i <= n) {
        printf("%d ", first);
        next = first + second;
        first = second;
        second = next;
        i++;
    }
    return 0;
}

// Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 
				
			

Infinite While Loop in C

In the loop if the condition never becomes false the loop runs forever. You should always include a false condition to avoid an infinite loop as it freezes the program.

				
					#include <stdio.h>
int main() {
    // 1 represents TRUE, so this condition never becomes False
    while (1) {
        printf("This will give an infinite loop\n");
    }
    return 0;
}  

// this will return the print statement infinite times
				
			

Nested While Loop

A while loop placed within the body of another while loop is referred to as a nested while loop.

 

Write a C Program to print the below pattern using the Nested while Loop

* * * 

* * * 

* * *

				
					#include <stdio.h>
int main() {
    int i = 1;
    // Outer Loop(Rows)
    while (i <= 3) {
        int j = 1;

        // Inner Loop (Columns)
        while (j <= 3) {
            printf("* ");
            j++;
        }
        printf("\n"); 
        i++;
    }
    return 0;
}

// * * * 
// * * * 
// * * * 

				
			
i (Row)j (Col)j <= 3ActionOutput (Current Line)
11TruePrint **
12TruePrint ***
13TruePrint ****
14False\n(End of line. Cursor moves down)
21TruePrint **
22TruePrint ***
23TruePrint ****
24False\n(End of line. Cursor moves down)
31TruePrint **
32TruePrint ***
33TruePrint ****
34False\n(End of line. Cursor moves down)
4-FalseStop Loop

Do-While Loop in C

The do-while loop in C is a looping construct that ensures the execution of the loop body at least once, even if the condition is initially false. This makes it ideal for menus, input validation and interactive programs. What Is a Do-While Loop?

A do-while loop is an exit-controlled loop:

  • The loop body runs first.The condition is checked after execution. Because of this, the loop always executes at least one time.
  • In writing the while statement it should always include a semicolon( ; )
Flowchart diagram of a C do-while loop: The flow enters the code block first, then moves to a decision diamond at the bottom to check the condition. If True, it loops back up; if False it exits.
The Exit-Control Loop: Notice the decision diamond is placed at the bottom. This structure guarantees that the code block executes at least once before any condition is checked.
				
					// Syntax of Do-While Loop in C
do
{
    // statements
}
while (condition);   // Semicolon ; after while(condition) is mandatory

				
			
				
					#include <stdio.h>

int main() {
    int number;

    do {
        printf("Enter a number greater than 10: ");
        scanf("%d", &number);
    }
    while (number <= 10); // If number is 10 or less, repeat!</mark>

    printf("Success! You entered: %d\n", number);

    return 0;
}

// Enter a number greater than 10: 12
// Success! You entered: 12

				
			

In the do-while loop the message prints at least once, even if the user enters invalid input.

 

Difference between While loop and Do-While loop

FeatureWhile LoopDo-While Loop
Loop typeEntry-controlledExit-controlled
Condition checkBefore executionAfter execution
Minimum execution0 timesAt least once
Semicolon neededNoYes
Use caseWhen execution depends on conditionWhen execution is mandatory

Applications of the do-while Loop in C

 

1. Menu-Driven Programs: Used where a menu must be displayed at least once and repeated based on user choice.

2. User Input Validation: Used when input must be accepted at least once, even if it is invalid, and repeated until it becomes valid.

3. Interactive Programs: Used in programs that require user interaction, such as games or command-based applications.

4. Retry Mechanisms: Used in scenarios involving retries, such as login attempts or confirmation prompts.

5. Loop-Based Decision Systems: Used when decisions depend on at least one execution, such as confirmation dialogs.

6. Embedded Systems Initialization: Used where initial setup or initialization must occur once before condition checking begins.

7. Transaction Processing: Used in applications where at least one transaction must be processed before deciding whether to continue.

Frequently Asked Questions (FAQs)

1) What is a do-while loop in C?

The do-while loop is an exit-controlled loop that checks the condition after executing the body. This guarantees the loop runs at least once, even if the condition is false from the start.

 

2) What is the difference between for loop and while loop in C?

Use a for loop when you know the exact number of iterations beforehand; it keeps the setup, condition, and update logic in one single line. When the number of iterations is unknown, a while loop is the best choice. It relies on a specific condition to stop.

 

3) When should we use a while loop in C?

A while loop should be used when:

• Execution depends strictly on a condition

• The number of iterations is not fixed

• The loop should not execute if the condition is false initially.