for loop in C programming with example

What is a loop?

Loops are used to execute the block of code several times according to the condition given in the loops. Every loop required initialization, condition, increment/decrement in the C programming language.

for loop in C

For loop is most used in C programming. When the programmer knows how many times a set of statements are to be executed, then for loop is used.

for loop consists of three different parts. The first part is an initialization, the second is testing the condition, and the third increment or decrement.

Syntax of for loop:

for(initialization; condition; increment or decrement)
{
      printf("Statement");
}

Flowchart of for loop:

Flowchart of for loop

for loop is the most used loop in C programming. for loop contains three parameters, initialization, condition and increment/decrement. The loop will continue to execute statements while the condition becomes true.

Example of for loop:

#include <stdio.h>
#include <stdlib.h>
int main()
{
   int i;
   for(i=1; i<=5; i++)
   {
       printf("Value is: %d\n", i);
   }
  return 0;
}

Output:

Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5

Steps to initialize a block code:

  1. Firstly initialize the code.
  2. Then, check the conditions.
  3. If it’s true it executes the for loop body.
  4. After execution, it evaluates the increment or decrement condition, again and again, follow from step 2.
  5. When the condition expression becomes false, it exists a loop.

Properties of for loop:

  • Loop is pre-tested.
  • A loop exists when the loop counter value is equal to the end value.

Nested for loop in C

Nested for loop means inside another for is called as nested for loop.

Example of nested for loop:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, j;
   for(i=0; i<1; i++)
   {
 for(j=0; j<3; j++)
 {
    printf("i: %d, j: %d\n", i, j);
 }
   }
   return 0;
}

Output:

i: 0, j: 0
i: 0, j: 1
i: 0, j: 2

Previous Lecture:

Data Types
Escape Character
Conditional statements-if-if-else

If you have any problem in solving your questions, then join our Telegram group or search @Learnsimply, we will help you.

Please write comments if you find anything incorrect in the for loop lecture.

Leave a Comment

en English
X