while loop in C | syntax

 

while loop in C

While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance.

                while loop in C

Here's the syntax for a while loop in C:

c
while (condition) {
// Code to be executed
}


Here's how a while loop works:

1. The condition inside the while is evaluated.
2. If the condition is true, the code block inside the while is executed.
3. After executing the code block, the condition is evaluated again.
4. If the condition is still true, the code block is executed again, and this process continues until the condition becomes false.
5. Once the condition becomes false, the loop terminates, and program control moves to the next statement after the while loop.
  1. Flowchart of while loop in C
    while loop in C


    Example of the while loop in C language:

    c
    #include <stdio.h>

    int main() {
    int i = 1; // Initialize a variable

    while (i <= 5) { // The condition
    printf("This is iteration %d\n", i);
    i++; // Increment the variable
    }

    return 0;
    }

    Output:

    csharp
    This is iteration 1
    This is iteration 2
    This is iteration 3
    This is iteration 4
    This is iteration 5

    Here's an example of a while loop in C that counts from 1 to 5:

    c
    #include <stdio.h>

    int main() {
    int count = 1;
    while (count <= 5) {
    printf("%d\n", count);
    count++;
    }

    return 0;
    }
  2. Output:
    1
    2
    3
    4
    5

Post a Comment

0 Comments