{ A destination to learn coding }

Iteration Statements

Iteration statements are also called as loops

In C there are 3 iteration statements.

  1. For Loop
  2. While Loop
  3. Do-while Loop

For Loop

For loop is the most commonly used loop. It consists of 3 expression- initialization expression, conditional expression and increment separated by semi-colons.

Syntax

for(initialization; condition; increment)
{
statement;
}

Example

for(i=0;i<10;i++)
{
  printf("Hello World\n");
}
printf("Done");

In the example above, i acts as the loop control variable. It is assigned value 0. After the initialization, the program control is passed to the conditional expression to test the condition. Here, if the condition is true, the statement is executed (In above code, printf("Hello World\n"); statement will be executed) After the execution of the statement, the program control is passed to the increment expression and i is incremented to 1.

After the increment expression, the loop iterates. It again tests for the condition i<10 and executes the statement if the condition is true.

In the code above, since the value of i is 1, the condition is true and the statement executes.
Again the value of i is incremented by 1 unit.
This way the loop iterates until the condition is false. When the conditional expression is false, the loop terminates and the program control is passed to the line of code which is immediately after the loop. (in above case to printf("Done");)

Try the code below
#include<stdio.h>
int main()
{
  int a,i; /*dont forget to declare the variables*/
  printf("Enter a number\n");
  scanf("%d",&a);

  for(i=0;i<10;i++)
  {
  printf("%d\n",a);
  a++;
  }

  return 0;
}

Note: The statements can either be empty, single line, or block of statements.
For single line statements, curly braces are not necessary. Nonetheless it is recommended to put to avoid confusions.

for(int a=10;a!=15;a++)
  printf("Hi\n"); /*this is a single line statement*/
This is a valid form
Also note that you must declare the variable before using it in the loop.

Try this
Printing table of any number
Display first 10 natural numbers
Find factorial of a number
Code to check for a prime number.
Fibonacci Series
You can even try printing patterns
C Codes