Friday, December 8, 2017

For Loop in C Programming

We used loops to execute a block of code several times.

Syntax of for loop
for ( variable initialization ;  condition ;  variable update )
{
      // body statement.
}

Variable Initialization : It allows us to assign value into a pre-declared variable or we can declare here at the same time, Variable initialization statement is executed once in the beginning of execution.

Condition : It decides whether loop needs to continue or not after checking the condition. If the condition is false then the loop will not be executed.

Variable update : We can update our variables here. Like increment, decrement etc.


Let’s look into the following program which will print “Hello world” 5 times.

#include <stdio.h>

int main() 
{
      for(int i = 1;  i <= 5;  i++)
      {
           printf("Hello World \n");
      }
      return 0;
}

Output
Hello World 
Hello World 
Hello World 
Hello World 
Hello World 

How it works

Step 1 : First we declare a variable name i and assign value of 1.

Step 2 : Then it will check either the condition ( i <= 5 ) is true or not. If the condition is true then it will go to the body statement. Otherwise it will be terminated.

Step 3 : In the body statement, there is only one print command and it will be executed.

Step 4 : After that, Update statement will be executed first time ( note that update statement will be executed form 2nd iteration and from 2nd iteration variable initialization will be ignored )

Step 5 : Start repeating from Step 2.


Look at program below


#include <stdio.h>

int main() 
{
      int i = 1;
      for( ;  i <= 5 ;  )
      {
           printf("Hello World \n");
           i++;
      }
      return 0;
}

Both programs are valid. In for loop we can either declare variable inside the loop or outside the loop as it will be executed only once. In this case we declare outside of for loop. Same as for updating variable. We increases variable inside the loop as we need to update the value every time.

Note : Semicolon separates each of these section. Any section can be empty but the semicolon must have to be there.



Previous Topic

Next Topic



No comments:

Post a Comment