Lesson 29 of 60 – while Loop in C
48%

while Loop in C

The while loop is used to repeatedly execute a block of code as long as a given condition is true. It is useful when the number of iterations is not necessarily known in advance.

Note: A while loop checks its condition before executing the loop body. If the condition is false at the beginning, the loop body will not execute even once.

1. What is a while Loop?

A while loop repeats a block of statements while its condition remains true.

while (condition)
{
    // statements
}

The condition is checked before every iteration.

2. Syntax of while Loop

while (condition)
{
    statement;
}

The condition must be written inside parentheses. The statements to be repeated are written inside the braces.

3. Simple while Loop

int i = 1;

while (i <= 5)
{
    printf("%d\n", i);
    i++;
}

Output:

1
2
3
4
5

The variable i is increased after every iteration.

4. Initialization Before while Loop

Unlike the initialization section of a for loop, a while loop normally requires the loop variable to be initialized before the loop.

int i = 1;

while (i <= 5)
{
    printf("%d ", i);
    i++;
}

Here, i starts with the value 1.

5. Condition in while Loop

The condition controls whether the loop continues.

int i = 1;

while (i <= 5)
{
    printf("%d ", i);
    i++;
}

The loop continues while i <= 5 is true. When i becomes 6, the condition becomes false and the loop stops.

6. Updating the Loop Variable

The loop variable should normally be changed inside the loop so that the condition can eventually become false.

int i = 1;

while (i <= 5)
{
    printf("%d ", i);
    i++;
}

The i++ statement increases the value of i by one.

7. Execution Flow of while Loop

The execution takes place in this order:

  1. Initialize the loop variable.
  2. Check the condition.
  3. If the condition is true, execute the loop body.
  4. Update the loop variable.
  5. Check the condition again.
  6. Repeat until the condition becomes false.

8. Printing Numbers from 1 to 10

int i = 1;

while (i <= 10)
{
    printf("%d\n", i);
    i++;
}

This program prints numbers from 1 to 10.

9. Printing Numbers from 10 to 1

int i = 10;

while (i >= 1)
{
    printf("%d ", i);
    i--;
}

Output:

10 9 8 7 6 5 4 3 2 1

The decrement operator -- decreases the value by one.

10. Printing Even Numbers

int i = 2;

while (i <= 10)
{
    printf("%d ", i);
    i += 2;
}

Output:

2 4 6 8 10

11. Printing Odd Numbers

int i = 1;

while (i <= 10)
{
    printf("%d ", i);
    i += 2;
}

Output:

1 3 5 7 9

12. Calculating Sum Using while Loop

int i = 1;
int sum = 0;

while (i <= 5)
{
    sum = sum + i;
    i++;
}

printf("Sum = %d", sum);

Output:

Sum = 15

13. Multiplication Table Using while

int number = 5;
int i = 1;

while (i <= 10)
{
    printf("%d x %d = %d\n",
           number, i, number * i);
    i++;
}

This program prints the multiplication table of 5.

14. while Loop with User Input

#include <stdio.h>

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

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

    while (i <= n)
    {
        printf("%d ", i);
        i++;
    }

    return 0;
}

The value entered by the user determines how many numbers are printed.

15. Factorial Using while Loop

int number = 5;
int factorial = 1;
int i = 1;

while (i <= number)
{
    factorial = factorial * i;
    i++;
}

printf("Factorial = %d", factorial);

Output:

Factorial = 120

16. while Loop with a Step Value

int i = 0;

while (i <= 20)
{
    printf("%d ", i);
    i += 5;
}

Output:

0 5 10 15 20

The loop variable increases by 5 after each iteration.

17. while Loop with if Statement

int i = 1;

while (i <= 10)
{
    if (i % 2 == 0)
    {
        printf("%d ", i);
    }

    i++;
}

The if statement allows the program to print only even numbers.

18. while Loop with Multiple Statements

int i = 1;

while (i <= 3)
{
    printf("Number = %d\n", i);
    printf("Hello\n");

    i++;
}

Both statements execute during every iteration of the loop.

19. while Loop and Character Input

char choice = 'y';

while (choice == 'y')
{
    printf("You selected yes.\n");

    printf("Continue? (y/n): ");
    scanf(" %c", &choice);
}

A while loop can also be controlled by a character condition.

20. Reading Values Until a Condition Changes

int number = 1;

while (number != 0)
{
    printf("Enter a number (0 to stop): ");
    scanf("%d", &number);
}

The loop continues until the user enters 0.

21. while Loop for Countdown

int count = 5;

while (count > 0)
{
    printf("%d\n", count);
    count--;
}

printf("Start!");

The loop counts downward and stops when count becomes 0.

22. while Loop with Logical Operators

int i = 1;

while (i <= 10 && i > 0)
{
    printf("%d ", i);
    i++;
}

Logical operators such as && and || can be used inside loop conditions.

23. while Loop That Does Not Execute

If the condition is false before the first check, the loop body is skipped.

int i = 10;

while (i < 5)
{
    printf("%d", i);
    i++;
}

Nothing is printed because 10 < 5 is false.

24. Common Mistake: Forgetting the Update

If the loop variable is not changed, the condition may remain true forever.

int i = 1;

while (i <= 5)
{
    printf("%d ", i);
}

Here, i always remains 1, so the condition remains true.

Correct:

int i = 1;

while (i <= 5)
{
    printf("%d ", i);
    i++;
}

25. Common Mistake: Wrong Update Direction

The update should move the loop variable toward making the condition false.

int i = 1;

while (i <= 5)
{
    printf("%d ", i);
    i--;
}

Here, i moves away from the stopping condition i > 5, so the loop does not terminate normally.

26. Common Mistake: Using Assignment Instead of Comparison

Use comparison operators such as == when you want to compare values.

int i = 1;

while (i == 1)
{
    printf("Hello\n");
    i++;
}

Here, == compares the values. The assignment operator = has a different purpose and should not be confused with comparison.

27. Complete Sum Program

#include <stdio.h>

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

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

    while (i <= n)
    {
        sum += i;
        i++;
    }

    printf("Sum = %d", sum);

    return 0;
}

This program calculates the sum of all integers from 1 to the number entered by the user.

28. Complete Multiplication Table Program

#include <stdio.h>

int main()
{
    int number;
    int i = 1;

    printf("Enter a number: ");
    scanf("%d", &number);

    while (i <= 10)
    {
        printf("%d x %d = %d\n",
               number, i, number * i);
        i++;
    }

    return 0;
}

29. Complete Factorial Program

#include <stdio.h>

int main()
{
    int number;
    int factorial = 1;
    int i = 1;

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

    if (number < 0)
    {
        printf("Factorial is not defined for negative integers.");
    }
    else
    {
        while (i <= number)
        {
            factorial *= i;
            i++;
        }

        printf("Factorial = %d", factorial);
    }

    return 0;
}

For larger values, an int can overflow, so appropriate data types and input limits should be considered.

30. Practice Programs Using while Loop

Practice the following programs:

  1. Print numbers from 1 to 100.
  2. Print numbers from 100 to 1.
  3. Print even numbers from 1 to 100.
  4. Print odd numbers from 1 to 100.
  5. Calculate the sum from 1 to N.
  6. Calculate the factorial of a number.
  7. Print a multiplication table.
  8. Print multiples of 5 up to 100.
  9. Read numbers until the user enters 0.
  10. Create a countdown program using a while loop.

Practice changing the condition and update statement to understand how the while loop works.

📌 Key Points

  • The while loop repeats statements while a condition is true.
  • The condition is checked before every iteration.
  • The loop body may execute zero times if the initial condition is false.
  • The loop variable is normally initialized before the loop.
  • The loop variable should usually be updated inside the loop.
  • A missing or incorrect update can cause an infinite loop.
  • A while loop can count upward or downward.
  • It can be combined with if statements and logical operators.
  • It is useful when the number of iterations depends on a condition.
  • Always make sure the loop has a clear stopping condition.

🧠 Quick Quiz

Question: When is the condition of a while loop checked?