Cover Image for C while loop
87 views

C while loop

The while loop is a control flow structure that allows you to repeatedly execute a block of code as long as a specified condition is true. It’s a pre-tested loop, which means that the condition is evaluated before each iteration, and if the condition is false initially, the loop body is never executed.

Here’s the basic syntax of a while loop:

C
while (condition) {
    // Code to be executed while the condition is true
}
  • condition: An expression or condition that is checked before each iteration. As long as this condition evaluates to true, the loop continues to execute.
  • The loop body is enclosed in curly braces {} and contains the code you want to repeat.

Here’s an example of a simple while loop that counts from 1 to 5:

C
#include <stdio.h>

int main() {
    int i = 1; // Initialize the loop control variable

    while (i <= 5) { // Condition: as long as i is less than or equal to 5
        printf("%d ", i); // Print the value of i
        i++; // Increment the loop control variable
    }

    return 0;
}

In this example:

  • The while loop starts with i equal to 1.
  • The condition i <= 5 is true, so the loop body is executed.
  • Inside the loop, the value of i is printed, and i is incremented by 1 (i++).
  • The loop continues to execute as long as the condition i <= 5 remains true.
  • When i becomes 6, the condition becomes false, and the loop terminates.

The output of this program will be 1 2 3 4 5.

It’s important to ensure that the condition specified in the while loop eventually becomes false to avoid infinite loops. You can use variables to control the loop, and the loop will continue executing until the condition is no longer met.

Here are some key points to remember when using while loops:

  • Initialize loop control variables before the while loop.
  • Update loop control variables inside the loop to eventually make the condition false.
  • Be cautious of infinite loops and ensure that the loop condition can be satisfied.
  • while loops are suitable for situations where you don’t know in advance how many iterations are needed.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS