C while loop

A while loop is a pre-tested loop. A while loop statement is used when a programmer doesn’t know how many times the code will be executed before starting the loop, as it depends upon users input. It can use to execute statement zero or more times.

Syntax of while loop:

The syntax of while loop in C language is given below:

Working of while loop:

  • initialization – Initialise loop counter.
    It is not necessary that a loop counter must only be an int. It can be a float.
    The loop counter can be incremented or decremented by any value, not necessarily 1.
  • while – It is a keyword
  • expression or condition – The parentheses after the while keyword contains a condition.
    Usually, it is a logical expression.
    It tests a loop counter using condition.
    The loop terminates when the condition becomes false.
  • { } – The statements within the pair of braces {} immediately after the while keyword is called the body of a while loop.
  • increment or decrement – It is useful to increment or decrement the loop counter
    The condition results in true(non zero) or false(zero).

Example:

Output:

As we have declared the value of i=1, which is called initialization.
The while loop condition is true i.e. 1 < 5. It prints the value of ‘i’ as shown in the output.
Next increment i by one i.e. i=2. Again the condition will check, 2 < 5.
And it will continue up to the condition is false.

Flowchart of while loop:

The flowchart of while loop shown below would help you to understand the operation of while loop.
while-loop

Ankit Wasankar

Senior Java Developer
Java 11 | Microservices | Reactjs | SQL

Help others by sharing the content!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.