For loop

Syntax of for loop

for(initialization; condition; updates) {
   statement1;
   statement2;
  ------------ 
}

Syntax Explained

  1. At first, initialization is performed.
  2. After the initialization condition test preform.
  3. If the condition evaluates true, then the block of the statements will be executed. block of the statement under the loop is known as the body of a loop.
  4. When control reaches the end of the body of the loop, control jumps to the updates section and statements in this section will be executed.
  5. After the update, condition again tested and if again condition evaluates true then cycle repeated again with the execution of the body of the loop then updates and again condition check.
  6. The loop breaks as soon as the condition becomes false and control jumps out of the loop and reaches the next statement written after the body of the loop.

Examples of for loop

for(i = 1; i <= 10; i++) {
    printf("%d ",i);
}
In for loop initialization and update section is optional to write but semcolon is still mandatory if you skip these section. Check the following code snippet for examples...
i = 1;
for(; i <= 10; i++) {
    printf("%d ",i);
}
i = 1;
for(; i <= 10; ) {
    printf("%d ",i);
    i++;
}
Similary if needed, multiple statements can be written in the initialization and update section. Each statement must be separated by a comma and executed from left to right in these sections. Check the following code snippet for examples...
for(i = 1; j = 1; i <= 10; i++) {
    printf("%d ",j);
    j += 2;
}
//prints 1 3 5 7 9 .....19
for(i = 1; j = 1; i <= 10; i++,j += 2) {
    printf("%d ",j);
}
//prints 1 3 5 7 9 .....19
If condition is missed in the for loop, then for loop treated as infinite loop because condition is treated as true by default in for loop.
for(;;) {
}

Another way to write the above code snippet is as follows...

for(;;);
If the condition is missing in while loop, its a compile-time error. To run the infinite loop while supplying a condition that is always true. See the following code snippets...
while() {
   statements;
}
//Produce a compile time error, due to condition missing
while(1) {
    statement;
}
//Represents an infinite loop because 1 is treated as true in C.
i = 1;
while(1) {
    printf("%d ",i);
    i++;
    
    if(i > 10) {
        break;
    }
}
//Prints 1 2 3 4 ......10
In the above code snippet an infinite loop is written and to terminate the loop we use the condition "i > 10" then break the loop. break jumps the control out of the current loop. This approach works when you write a big logic and don't guess a condition to break the loop.

For loop in C | Video Tutorial in Hindi