C while loop


The most basic loop in C is the while loop and it is used is to repeat a block of code. A while loop has one control expression (a specific condition) and executes as long as the given expression is true. Here is the syntax :


while (condition)

In while loop first the condition (boolean expression) is tested; if it is false the loop is finished without executing the statement(s). If the condition is true, then the statements are executed and the loop executes again and again until the condition is false.
If there is only one statement, the braces may be omitted; however, it is good practice to always include the braces.

See the flowchart :

c  while loop flowchart

A Simple While Loop Example -1

The following program prints n asterisks.

asteric prints in C

Example - 2:

The following program prints two numbers.

#include <stdio.h>
int m = 5;
int n = 0;
while (m > n)
printf("m = %d n = %d\n",m,n );


m = 5 n = 0
  m = 4 n = 1
  m = 3 n = 2


The loop will terminate when m becomes equal to or lesser than n, hence m <= n is the terminating condition of the while loop.

The loop has executed 3 times.

The condition m>n has checked 4 times.

First time : m = 5 and n = 0, this time the condition is true, so loop is executed.
Second time : m = 4, and n = 1. Again the condition is true, so the loop is executed.
Third time : m = 3 and n = 2. Again the condition is true so the loop is executed.
Fourth time : m = 2 and n = 3. Now the condition is false, hence loop is not executed.
Therefore this is the last time the condition m>n is checked in the program.

Here is the flowchart of the above program

c prime number flowchart

Previous: C for loop
Next: C do while loop

Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

What does (x ^ 0x1) != 0 mean?

The XOR operation (x ^ 0x1) inverts bit 0. So the expression effectively means: if bit 0 of x is 0, or any other bit of x is 1, then the expression is true.

Conversely the expression is false if x == 1.

So the test is the same as:

if (x != 1)

and is therefore (arguably) unnecessarily obfuscated.

Ref :https://bit.ly/2NIisQM

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook