Friday, March 3, 2017

How for loop works in programming language?

How for loop works in programming language?

Working of for loop

A for loop is used to repeat a specific block of code number of times. For example, you want to print a table for 2, 3, 4 or so on, or you want to print prime numbers between 1-1000 and if you want to check the grades of every student in a class. So, here we use loops. And for loop is one of the mostly use loop among the others (while loop and do while loop).
The advantage of for loop is you know exactly how many times the loop will execute before the loop starts.

For loop syntax is:
for(exp1; exp2; exp3){
statements1
}
expressions can be initialization, condition and increment/decrement.
Here is the flow of control in a for loop −
  • The exp1 (initialization) step is executed first, and only once. This step used to declare and initialize any loop control variables(variables can be i, j, a, b etc.).
  • Next, the exp2 condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the for loop.
  • After the body of the for loop executes, the flow of control jumps back up to the increment/decrement statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
  • The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates.


Let’s take an example:
#include<stdio.h>
void main(){
int i;
for(i=0;i<=5;i++){
printf(“%d”, i);
}
}
Now what this loop is doing. First it initializes i with 0. Then it checks condition if i(which is 0 right now) is less than 5 or equal to 5 or not. If the condition is true then it’ll print the value of i and which is right now is 0. And then the control goes to the increment section. And the increment section now increment the value of i with 1. Now the value of i becomes 1. And then again it checks the condition. If the given condition is true. The control goes to the body of the loop. And the body of the loop execute.
The whole loop execute until the condition becomes false. When the condition becomes false. The loop terminates. It means that the loop stops now and control goes to the next statements.

No comments:

Post a Comment