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)
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.
|Flowchart of for loop in C – Image Source|
Anyways let’s try to understand this loop with one example.
Lets try to understand this program.
The program is quite easy to understand. In the beginning I have declared x variable as int. After that I have started for loop with 3 arguments (like in syntax). After that I have written printf() function. As I want to execute only one function after for keyword, that’s why I dropped the braces too.
- It is important to understand the execution of this program. As I have used for loop for this time. So lets get started.
- Program starts and entered in the for loop. I have initialize the for loop with the value x=0.
- After initialization the control will shift to check the condition. The condition turns to be true, as x is smaller than 10.
- Now remember after the condition checked, the control will shift to the printf() function (body of for loop). It will print the message on screen.
- Then in last the control will shift to the incrimination part. So the value of x will be incremented to 1.
- Now it will again check the condition. It will again turns true. So it will again print the message.
- This process will go on until the value of x becomes 10. When x holds the value 10 then it will fail with the condition. So the control will come outside the loop.
As I have said earlier for loops are used more widely than while loops. Its just due to its compact syntax. It is very important to understand the execution of for loop to write good programs using it.
For practice of this loop you can try below program.
Write a program to print your name 10 times. Try to analyse the execution of program by giving different conditions.