While loop in c programming language





In the C programming language, a while loop is a control flow statement that allows you to repeatedly execute a block of code as long as a specified condition is true. The syntax of a while loop in C is as follows:

while (condition) {
    // Code to be executed repeatedly
    // This code will execute as long as the condition remains true
}

Here's a breakdown of how it works:

  • The condition is an expression that evaluates to either true (non-zero) or false (zero).
  • The code inside the curly braces {} is the body of the loop. It contains the statements that you want to execute repeatedly.
  • When the while loop is encountered, the condition is evaluated first. If the condition is true, the body of the loop is executed. After the body executes, the condition is evaluated again. If it is still true, the body executes again. This process repeats until the condition becomes false.
  • If the condition is false initially, the body of the loop is never executed, and the program continues with the statement immediately following the loop.



Here's a basic program in C that demonstrates the usage of a while loop. This program prompts the user to enter a number, and it keeps printing the square of that number until the user enters 0.

#include <stdio.h>

int main() {
    int num;

    // Prompt the user to enter a number
    printf("Enter a number (0 to exit): ");
    scanf("%d", &num);

    // While the entered number is not zero
    while (num != 0) {
        // Calculate and print the square of the number
        printf("Square of %d is %d\n", num, num * num);

        // Prompt the user to enter another number
        printf("Enter a number (0 to exit): ");
        scanf("%d", &num);
    }

    printf("Exiting the program.\n");

    return 0;
}
Output:
Enter a number (0 to exit): 5
Square of 5 is 25
Enter a number (0 to exit): 4
Square of 4 is 16
Enter a number (0 to exit): 0
Exiting the program.


Best use of while loop When you need to repeatedly prompt the user for input until they provide valid data, a while loop can be used. For example, asking the user to enter a positive number:

#include <stdio.h>

int main() {
    int num;
    
    // Keep prompting until a positive number is entered
    while (1) {
        printf("Enter a positive number: ");
        scanf("%d", &num);
        
        if (num > 0) {
            printf("You entered: %d\n", num);
            break;  // Exit the loop
        } else {
            printf("Invalid input. Please enter a positive number.\n");
        }
    }
    
    return 0;
}
Output:
Enter a positive number: -6
Invalid input. Please enter a positive number.
Enter a positive number: -101
Invalid input. Please enter a positive number.
Enter a positive number: 5
You entered: 5


The while must test a condition that will eventually become false, otherwise the loop would be executed forever, indefinitely.

#include <stdio.h>
int main()
{
    int i = 1;
    while (i <= 10)
        printf("%d\n", i);
    return 0;
}
Output:
1
1
1
1

infinity


This is an indefinite loop, since i remains equal to 1 forever. The correct form would be as under:

#include <stdio.h>
int main()
{
    int i = 1;
    while (i <= 10)
    {
        printf("%d\n", i);
        i = i + 1;
    }
    return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10


Instead of incrementing a loop counter, we can decrement it and still manage to get the body of the loop executed repeatedly. This is shown below.

#include <stdio.h>
int main()
{
    int i = 5;
    while (i >= 1)
    {
        printf("Make the computer literate! : %d\n",i);
        i = i - 1;
    }
}
Output:
Make the computer literate! : 5
Make the computer literate! : 4
Make the computer literate! : 3
Make the computer literate! : 2
Make the computer literate! : 1


It is not necessary that a loop counter must only be an int. It can even be a float.

#include <stdio.h>
int main()
{
    float a = 10.0;
    while (a <= 10.5)
    {
        printf("Raindrops on roses...");
        printf("...and whiskers on kittens\n");
        a = a + 0.1;
    }
    return 0;
}
Output:
Raindrops on roses......and whiskers on kittens
Raindrops on roses......and whiskers on kittens
Raindrops on roses......and whiskers on kittens
Raindrops on roses......and whiskers on kittens
Raindrops on roses......and whiskers on kittens


Even floating point loop counters can be decremented. Once again, the increment and decrement could be by any value, not necessarily 1.

What will be the output of the following program:

#include <stdio.h>
int main()
{
    int i = 1;
    while (i <= 10)
        ;
    {
        printf("%d\n", i);
        i = i + 1;
    }
    return 0;
}
Output:
Loop will execute infinite and will not print anything as output.

This is an indefinite loop, and it doesn’t give any output at all. The reason is, we have carelessly given a ; after the while.



C program to repeatedly prompt the user to input a number, calculate its square, and inquire whether they wish to input another number, utilizing a while loop and standard input/output functions?

#include <stdio.h>

int main() {
    char user_choice = 'y';
    int number;

    while (user_choice == 'y') {
        printf("Enter a number: ");
        scanf("%d", &number);
        printf("Square of %d is %d\n", number, number * number);
        printf("Want to enter another number? (y/n): ");
        fflush(stdin);
        scanf(" %c", &user_choice);
    }

    return 0;
}
Output:
Enter a number: 5
Square of 5 is 25
Want to enter another number? (y/n): y
Enter a number: 8
Square of 8 is 64
Want to enter another number? (y/n): n