C while Loop

Introduction

In the previous chapter, we learned about the for loop in C. In this chapter, we will focus on the while loop. The while loop is another fundamental control flow structure that allows you to execute a block of code repeatedly based on a given condition. Unlike the for loop, the while loop is more suitable when the number of iterations is not known in advance.

What is a while Loop?

A while loop is used to repeatedly execute a block of code as long as the specified condition is true. The condition is evaluated before the execution of the loop body, which means the loop body may not execute at all if the condition is initially false.

Syntax

The basic syntax of a while loop in C is as follows:

while (condition) {
    // Code to be executed repeatedly
}
  • condition: This expression is evaluated before each iteration of the loop. If it evaluates to true, the loop body is executed. If it evaluates to false, the loop terminates.

Example: Simple while Loop

Let’s look at a simple example to understand how the while loop works.

Example: Printing Numbers from 1 to 5

#include <stdio.h>

int main() {
    int i = 1; // Initializing loop counter

    while (i <= 5) { // Condition
        printf("%d\n", i); // Printing the value of i
        i++; // Updating the loop counter
    }

    return 0; // Returning 0 to indicate successful execution
}

Output:

1
2
3
4
5

Detailed Steps

  1. Initialization: The loop counter i is initialized to 1.
  2. Condition: The condition i <= 5 is checked. Since it is true, the loop body is executed.
  3. Execution: The printf statement prints the value of i.
  4. Update: The loop counter i is incremented by 1.
  5. Repeat: Steps 2-4 are repeated until the condition i <= 5 becomes false.

Infinite while Loop

A while loop can run indefinitely if the condition always evaluates to true. This is known as an infinite loop.

Example: Infinite while Loop

#include <stdio.h>

int main() {
    int i = 1;

    while (1) { // Infinite loop
        printf("This is an infinite loop.\n");
        if (i == 5) {
            break; // To break the loop, you can use a break statement
        }
        i++;
    }

    return 0; // Returning 0 to indicate successful execution
}

Output:

This is an infinite loop.
This is an infinite loop.
This is an infinite loop.
This is an infinite loop.
This is an infinite loop.

Using break and continue in while Loops

Break Statement

The break statement is used to exit the loop prematurely, regardless of the condition.

Example: Using break in while Loop

#include <stdio.h>

int main() {
    int i = 1;

    while (i <= 5) {
        if (i == 3) {
            break; // Exit the loop when i is 3
        }
        printf("%d\n", i);
        i++;
    }

    return 0; // Returning 0 to indicate successful execution
}

Output:

1
2

Continue Statement

The continue statement skips the current iteration of the loop and proceeds to the next iteration.

Example: Using continue in while Loop

#include <stdio.h>

int main() {
    int i = 1;

    while (i <= 5) {
        if (i == 3) {
            i++;
            continue; // Skip the iteration when i is 3
        }
        printf("%d\n", i);
        i++;
    }

    return 0; // Returning 0 to indicate successful execution
}

Output:

1
2
4
5

Nested while Loops

You can use nested while loops to handle more complex scenarios, such as iterating over a 2D array or performing matrix operations.

Example: Nested while Loop

#include <stdio.h>

int main() {
    int i = 1;

    while (i <= 3) { // Outer loop
        int j = 1;
        while (j <= 2) { // Inner loop
            printf("i = %d, j = %d\n", i, j); // Printing the values of i and j
            j++;
        }
        i++;
    }

    return 0; // Returning 0 to indicate successful execution
}

Output:

i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2

Simple C Programs to Demonstrate while Loop

Program 1: Sum of First N Natural Numbers

Example:

#include <stdio.h>

int main() {
    int n, sum = 0, i = 1;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    while (i <= n) {
        sum += i; // Adding i to sum
        i++; // Updating loop counter
    }

    printf("Sum of first %d natural numbers is: %d\n", n, sum);

    return 0; // Returning 0 to indicate successful execution
}

Output:

Enter a positive integer: 5
Sum of first 5 natural numbers is: 15

Program 2: Factorial of a Number

Example:

#include <stdio.h>

int main() {
    int n, factorial = 1, i = 1;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    while (i <= n) {
        factorial *= i; // Multiplying i to factorial
        i++; // Updating loop counter
    }

    printf("Factorial of %d is: %d\n", n, factorial);

    return 0; // Returning 0 to indicate successful execution
}

Output:

Enter a positive integer: 5
Factorial of 5 is: 120

Program 3: Multiplication Table

Example:

#include <stdio.h>

int main() {
    int n, i = 1;

    printf("Enter an integer: ");
    scanf("%d", &n);

    while (i <= 10) {
        printf("%d x %d = %d\n", n, i, n * i); // Printing multiplication table
        i++; // Updating loop counter
    }

    return 0; // Returning 0 to indicate successful execution
}

Output:

Enter an integer: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Program 4: Printing an Array

Example:

#include <stdio.h>

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);
    int i = 0;

    while (i < n) {
        printf("Element %d: %d\n", i, arr[i]); // Printing each element of the array
        i++; // Updating loop counter
    }

    return 0; // Returning 0 to indicate successful execution
}

Output:

Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50

Conclusion

The while loop is a powerful and flexible control flow statement in C. It allows you to execute a block of code repeatedly based on a given condition. By understanding and using the while loop, you can write more efficient and concise code for scenarios where the number of iterations is not known in advance. You can also use nested while loops and control statements like break and continue to handle more complex scenarios and achieve greater control over your program’s execution flow.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top