🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

While Loop

While Loop

While Loop

A While loop is also called a pre-tested loop. A while loop allows a piece of code in a program to be executed multiple times, depending upon a given test condition which evaluates to either true or false. The while loop is mostly used in cases where the number of iterations is not known. If the number of iterations is known, then we could also use a for loop.

Syntax for using a while loop:

        
while (condition test)
{
    // Set of statements
}
        
    

The body of a while loop can contain a single statement or a block of statements. The test condition may be any expression that should evaluate as either true or false. The loop iterates while the test condition evaluates to true. When the condition becomes false, the program control passes to the line immediately following the loop, which means, it terminates.

Example:

        
#include <stdio.h>

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

Output:

0 1 2 3 4 5

Properties of the while loop:

  • A conditional expression written in the brackets of while is used to check the condition. The Set of statements defined inside the while loop will execute until the given condition returns false.
  • The condition will return 0 if it is true. The condition will be false if it returns any nonzero number.
  • In the while loop, we cannot execute the loop until we do not specify the condition expression.
  • It is possible to execute a while loop without any statements. This will give no error.
  • We can have multiple conditional expressions in a while loop.
  • Braces are optional if the loop body contains only one statement.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.