Programming for Problem Solving (3110003)

BE | Semester-1   Winter-2019 | 07-01-2020

Q5) (b)

Explain for loop with example.

for loop provides a more concise loop control structure. The general form of the for loop is:

for (initialization; test condition; increment)
       body of the loop;
  • When the control enters for loop, the variables used in for loop are initialized with the starting value such as i=0, count=0. Initialization part will be executed exactly one time.
  • Then it is checked with the given test condition. If the given condition is satisfied, the control enters into the body of the loop. If the condition is not satisfied then it will exit the loop.
  • After the completion of the execution of the loop, the control is transferred back to the increment part of the loop. The control variable is incremented using an assignment statement such as i++.
  • If the new value of the control variable satisfies the loop condition then the body of the loop is again executed. This process goes on till the control variable fails to satisfy the condition.
  • for loop is also an entry control loop because the first control-statement is executed and if it is true then only the body of the loop will be executed.
void main(){
int i;
int sum=0;
for(i=1; i < = 10; i++) { 
    sum = sum + i;
printf(“%d”, sum); 
We can include multiple expressions in any of the fields of for loop provided that we separate such expressions by commas.

For example:
for( i = 0; j = 100; i < 10 && j>50; i++, j=j-10)