Wednesday, 9 May 2018

while loop in C

while loop in C

Till now we have learnt about decision control instructions or the programs which will execute as the way they are programmed i.e. sequentially. However its not compulsory that we want to do some task inside a program for only one time.
Suppose we want to make a program which will print your name 5 times. Then it will be very ineffective way to use the printf() function for 5 times. Instead of it we should look for something that will do that task for specific number of times automatically.

Well this is indeed possible. This is where loops comes in action. Loops are generally used to perform some task specific number of times. Similar to decision control instructions, in loops we also have to give some condition. And the program will execute task until the condition turns to be true.

There are three types of loops in C programming.

1. while
2. for
3. do while

while loop in C
This is the first loop and the second most commonly used loop in programs. It is generally used to execute a set of statements fixed number of times. Generally programmers use this loop when they already know how many times the task should be executed.

Syntax of while loop
initialize loopcounter
while (condition)
execute this
and this…
increment loop counter

What is loop counter?
As I told you earlier that compiler doesn’t know how many times you want to perform some task. So to instruct the compiler we use loop counter. As its name suggests, it counts and instruct the while loop to stop executing the task.
Flowchart of While Loop in CC program to display a name 5 times on the screen


void main()
 int x=0;
 while (x<5)
  printf(" n");