While Loop in C: Iteration with Conditional Control

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

 

While Loop in C

A while loop in C is a control flow statement used to execute a block of code repeatedly as long as a specified condition remains true. It’s a flexible way to iterate over a sequence of values or perform actions until a certain condition is met.

Syntax:

while (condition) {
    // Code to be executed
}
  • Condition: An expression that is evaluated before each iteration. If the condition is true, the loop body is executed. If it’s false, the loop terminates.

Example:

int i = 0;
while (i < 5) {
    printf("Hello, world!n");
    i++;
}

 

In this example:

  • i = 0 initializes the loop variable i.
  • i < 5 is the condition that checks if i is less than 5.
  • The loop body (printf("Hello, world!n")) is executed as long as the condition is true.
  • i++ increments i after each iteration.

Common Uses:

  • Iterating over arrays or strings.
  • Counting or summing values.
  • Generating sequences of numbers.
  • Reading input from the user until a specific condition is met.

Key Points:

  • The while loop is a control flow statement used for iteration.
  • The condition is evaluated before each iteration.
  • The loop body is executed as long as the condition is true.
  • Be careful to avoid infinite loops by ensuring that the condition eventually becomes false.

Example with a User-Defined Condition:

int number;

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

while (number <= 0) {
    printf("Please enter a positive number: ");
    scanf("%d", &number);
}

printf("You entered: %dn", number);

This example uses a while loop to prompt the user to enter a positive number until a valid input is provided.

The while loop in C is used to evaluate a test condition and iterate over the loop body until the condition returns True. The loop ends when the condition returns False. This loop is also known as a pre-tested loop because it is commonly used when the number of iterations is unknown to the user ahead of time.

Related Posts

Leave a Reply