For Loop Statement in C With Example


For Loop Statement in C With Example

For loop statement in C is used to execute and repeat a block of statements based on a certain condition. It has the following form:

Syntax:-

for(<initial value>; <condition>; <increment>)
{
<statement block>
}

whereas the <initial value> is the kind of assignment expression that initializes the value of a variable.
<condition> is a relational or logical expression that will have the value of true or false.
<increment> is the incremented value of the variable which will be added every time if the condition is true.

  • When the statement block is executed, the computer assigns the initial value to the variable and the condition is evaluated.
  • If the value of the condition is true, the statement block will be executed.
  • Now the value of the variable is incremented and the condition is evaluated again and repeated until the value of the condition is false.

Let us take an example below

Also read, Greatest of Three Numbers in C Using Nested If

Print natural numbers from 1 to n using for loop statement in C

Complete Code:-

#include <stdio.h>
main()
{
  int n, i;
  printf("Enter the value to n :");
  scanf("%d",&n);
  /*Loop to generate and print natural numbers*/
  for(i=0;i<n;i++)
  {
      printf("\n %d",i);
  }
}

After running the above program, the user has to enter the value to n and then press the ENTER key. Now the program will be executed and the result will be displayed as shown below

Enter the value to n :10

0
1
2
3
4
5
6
7
8
9
Process returned 0 (0x0) execution time : 2.251 s
Press any key to continue.

Conclusion:- I hope this tutorial will help you to understand the overview of for loop statement. If there is any doubt then please leave a comment below.


Leave a Comment