Wednesday, 9 May 2018

For loop in C – Part 1

Till now we have learnt about the while loop. We have also seen some common errors made by beginners while write loop control structure. If you see some big complex program then you will notice that program mainly contains only for loop. Now an obvious question which may hit your mind.
Why for loops are used more frequently than while loops?
Well the answer of this question resides in its syntax. For loop is generally used to implement a loop control structure, when programmer knows how many times he wants to execute a set of statements. Well it is not compulsory to use for loop in only those conditions. You can implement it anytime.

General Syntax of for loop in C is given below.


for(loop_counter_initialize; Condition; Loop_Counter_incremented)
do this..;
and this..;

As you can see the syntax of for loop is quite compact. While using for loop, one doesn’t want have to write the loop counter explicitly.

So for loop is divided into three parts.

1. Initialization of loop counter
2. Condition of expression to check
3. Increment of loop counter

Truly speaking these 3 parts can replaced with any valid expression. It means we can also use functions like scanf() and printf() in spite of these 3 parts. We will learn about it in the next tutorial.