While Loop

Introduction

The while loop is a fundamental control structure in C that repeatedly executes a block of code as long as a specified condition remains true. Unlike the for loop which is typically used when the number of iterations is known, the while loop is ideal for situations where you need to repeat code based on a condition that may change during execution, and you don’t know in advance how many times the loop will run.

The while loop is particularly useful for input validation, menu systems, and situations where you need to process data until a certain condition is met. It provides a clean and readable way to implement repetitive logic based on dynamic conditions.

Key Concepts

Condition-Based Repetition: The loop continues as long as the condition evaluates to true (non-zero).

Pre-Test Loop: The condition is checked before each iteration, so the loop body may not execute at all if the condition is initially false.

Variable Loop Count: The number of iterations is not predetermined and depends on when the condition becomes false.

Loop Control: Proper management of variables that affect the condition is crucial to avoid infinite loops.

While Loop Syntax

Basic Syntax

while (condition) {
    // Code to be executed repeatedly
    // Must include something that eventually makes condition false
}

Simple Example

#include <stdio.h>
int main() {
    int count = 1;
    
    while (count <= 5) {
        printf("Count: %d\n", count);
        count++;  // Important: update the condition variable
    }
    
    return 0;
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

How While Loop Works

Execution Flow

  1. Check Condition: Evaluate the condition expression
  2. If True: Execute the loop body
  3. Repeat: Go back to step 1
  4. If False: Exit the loop and continue with next statement

Important Points

  • The condition is checked before each iteration
  • If the condition is false initially, the loop body never executes
  • The loop continues until the condition becomes false
  • You must ensure something in the loop body eventually changes the condition

Common While Loop Patterns

Pattern 1: Input Validation

#include <stdio.h>
int main() {
    int age;
    
    printf("Enter your age (1-120): ");
    scanf("%d", &age);
    
    while (age < 1 || age > 120) {
        printf("Invalid age! Please enter age between 1-120: ");
        scanf("%d", &age);
    }
    
    printf("Your age is: %d\n", age);
    return 0;
}

Pattern 2: Menu System

#include <stdio.h>
int main() {
    int choice;
    
    while (1) {  // Infinite loop
        printf("\n=== MENU ===\n");
        printf("1. Option A\n");
        printf("2. Option B\n");
        printf("3. Exit\n");
        printf("Choose: ");
        scanf("%d", &choice);
        
        if (choice == 1) {
            printf("You selected Option A\n");
        } else if (choice == 2) {
            printf("You selected Option B\n");
        } else if (choice == 3) {
            printf("Goodbye!\n");
            break;  // Exit the loop
        } else {
            printf("Invalid choice!\n");
        }
    }
    
    return 0;
}

Pattern 3: Processing Until Sentinel

#include <stdio.h>
int main() {
    int number, sum = 0;
    
    printf("Enter numbers (0 to stop): ");
    scanf("%d", &number);
    
    while (number != 0) {
        sum += number;
        printf("Enter next number (0 to stop): ");
        scanf("%d", &number);
    }
    
    printf("Sum of all numbers: %d\n", sum);
    return 0;
}

While vs For Loop Comparison

When to Use While Loop

  • Unknown number of iterations
  • Condition-based repetition
  • Input validation
  • Menu systems
  • Processing data until end condition

When to Use For Loop

  • Known number of iterations
  • Array processing
  • Counting operations
  • Mathematical sequences

Example: Same Task, Different Approaches

// Using for loop (when count is known)
for (int i = 1; i <= 10; i++) {
    printf("%d ", i);
}

// Using while loop (equivalent)
int i = 1;
while (i <= 10) {
    printf("%d ", i);
    i++;
}

Important Points

  • Always Update Condition Variables: Ensure variables used in the condition are modified within the loop
  • Avoid Infinite Loops: Make sure the condition will eventually become false
  • Initialize Before Loop: Initialize loop control variables before the while statement
  • Check Boundary Conditions: Test what happens when the condition is initially false
  • Use Break/Continue: Use these statements for additional loop control when needed

Common Applications

Example 1: Factorial Calculator

#include <stdio.h>
int main() {
    int n = 5;
    int factorial = 1;
    int i = 1;
    
    while (i <= n) {
        factorial *= i;
        i++;
    }
    
    printf("Factorial of %d is %d\n", n, factorial);
    return 0;
}

Example 2: Digit Counter

#include <stdio.h>
int main() {
    int number = 12345;
    int count = 0;
    
    while (number > 0) {
        number /= 10;  // Remove last digit
        count++;
    }
    
    printf("Number of digits: %d\n", count);
    return 0;
}

Example 3: Simple Game

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    srand(time(NULL));
    int secret = rand() % 100 + 1;
    int guess, attempts = 0;
    
    printf("Guess the number (1-100)!\n");
    
    while (1) {
        printf("Enter your guess: ");
        scanf("%d", &guess);
        attempts++;
        
        if (guess == secret) {
            printf("Congratulations! You got it in %d attempts!\n", attempts);
            break;
        } else if (guess < secret) {
            printf("Too low! Try again.\n");
        } else {
            printf("Too high! Try again.\n");
        }
    }
    
    return 0;
}

Common Mistakes and Solutions

Mistake 1: Infinite Loop

// Wrong - infinite loop
int i = 1;
while (i <= 10) {
    printf("%d ", i);
    // Missing i++ - i never changes!
}

// Correct
int i = 1;
while (i <= 10) {
    printf("%d ", i);
    i++;  // Update the control variable
}

Mistake 2: Off-by-One Errors

// Be careful with conditions
int i = 1;
while (i < 10) {    // Runs 9 times (1 to 9)
    printf("%d ", i);
    i++;
}

while (i <= 10) {   // Runs 10 times (1 to 10)
    printf("%d ", i);
    i++;
}

Mistake 3: Uninitialized Variables

// Wrong - uninitialized variable
int count;  // Contains garbage value
while (count < 5) {
    printf("%d ", count);
    count++;
}

// Correct - initialize first
int count = 0;
while (count < 5) {
    printf("%d ", count);
    count++;
}

Loop Control Statements

Break Statement

int i = 1;
while (i <= 10) {
    if (i == 6) {
        break;  // Exit loop when i equals 6
    }
    printf("%d ", i);
    i++;
}
// Output: 1 2 3 4 5

Continue Statement

int i = 0;
while (i < 10) {
    i++;
    if (i % 2 == 0) {
        continue;  // Skip even numbers
    }
    printf("%d ", i);
}
// Output: 1 3 5 7 9

Advanced Example: Text Processing

#include <stdio.h>
#include <ctype.h>

int main() {
    char text[] = "Hello World 123!";
    int i = 0;
    int letters = 0, digits = 0, others = 0;
    
    while (text[i] != '\0') {  // Process until end of string
        if (isalpha(text[i])) {
            letters++;
        } else if (isdigit(text[i])) {
            digits++;
        } else {
            others++;
        }
        i++;
    }
    
    printf("Letters: %d\n", letters);
    printf("Digits: %d\n", digits);
    printf("Others: %d\n", others);
    
    return 0;
}

Summary

The while loop is a powerful control structure that provides condition-based repetition in C programming. It’s ideal for situations where the number of iterations is unknown and depends on dynamic conditions. Key advantages include flexibility in handling varying iteration counts, suitability for input validation and menu systems, and clear expression of condition-based logic. Important considerations include proper initialization of control variables, ensuring the condition eventually becomes false to avoid infinite loops, and understanding the pre-test nature of the loop. The while loop complements the for loop by handling scenarios where iteration count is not predetermined, making it an essential tool for creating responsive and interactive programs. Mastering while loops enables programmers to handle user input validation, implement menu-driven programs, and process data streams effectively.


Part of BCA Programming with C Course (UGCOA22J201)