Site icon TestingDocs.com

C while Loop

Table of Contents

Toggle

Overview

C while loop allows us to repeat a statement or group of statements more than once. The programmer can use this loop when the number of iterations is not known beforehand. For example, to iterate until some condition is true/false.

Syntax

The general syntax of the C while loop is as follows:

while(condition)
{
// while loop statements
}

The while loop executes until the condition is evaluated to be true. The while loop is a pre-test loop. It tests the condition before executing the loop block or statements. The loop might not execute at all if the condition is false when the condition is checked for the first time.

Example

 

/**
**********************************
* Program Description:
*   C while Loop Statement Demo
* Filename  : whileDemo.c
* C Tutorials - www.TestingDocs.com
*************************************
*/
#include<stdio.h>
int main()
{
    int i = 1;// declare variable
    /* while loop statement */
    while(i <= 10)
    {
        printf(" Loop Iteration (%d) \n",i);
		i++;
    } // end while loop

    return 0;
} // end main

In this example, the variable i is declared and initialized to 1. The while loop will be executed until the condition i < = 10 is true. In the loop body, we are incrementing the value of the i variable. For each while loop iteration, the value of the i is increased by 1. The loop will exit when i become 11. The while loop condition i < = 10 would evaluate to false when i reach 11.

Exit mobile version