For Loop in C

In C and all other modern programming languages, iteration statements (also called loops) allow a set of instructions to be repeatedly executed until a certain condition is reached. 

In For loop this condition is predetermined.

In another way we can say, A loop can be used to tell a program to execute statements repeatedly. Or we can say that a loop repeatedly executes the same set of instructions until a termination condition is met.

For loop is helpful while writing complex logic and multiple loops.

The functional aspect of all the loops is the same, the only syntax is different.

Syntax:-

Now let’s understand the Syntax of for loop.

Three things are very important in the loop

  1. First is the initialization.
  2. Second is Condition / Termination.
  3. Third is Increment / Decrement.

Functioning of For Loop..!

Let’s understand the functioning of the loop with the help of an example.

Q. Run a for loop to print the numbers between the range of 1 to 9.

The following code will print the numbers between the range of 1 to 9.

Code:

C Program

#include<stdio.h>

int main()
{
    int i;
    for(i=1;i<10;i++)
    {
        printf("%d ",i);
    }
}

Output: 1 2 3 4 5 6 7 8 9

Let’s understand what is happening inside the loop.

  1. First Computer reaches the part of initialization that is ‘i’ equal to 1.  
  2. Next, the computer checks the termination condition. I.e Computer checks whether the ‘i’ is less than 10 or not. but currently the value of ‘i’ is 1, So 1 is definitely less than 10. The result is True.
  3. Now, The computer executes the code which is present inside the block of the for loop.
  4. After completing the execution of the code which is inside the loop the control flow goes to the Increment / Decrement condition of the loop.
  5. Now,It performs the Increment / Decrement operation (i.e. Now ‘i’ becomes 2 as we are incrementing the ‘i’ value by one i++).
  6. After that the computer again checks the termination condition (i.e If ‘i’ is less than 10 or not). Currently the condition is true i.e  2 < 10.
  7. Now, The computer executes the code which is present inside the block of the for loop. And this loop continues to run until the termination condition becomes false.
  8. Once the condition becomes false i.e ‘i’ becomes greater than or equal to 10. The loop terminates and the computer starts the execution of the code which is present below the for loop.

This was all about the for loop in C language.

Special thanks to Abhishek Yadav for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article