For Loop syntax

For loop stars with "for" keyword and three parameters enclosed within a first bracket. Three parameters are -

  1. Initialization statements
  2. Condition of the looping
  3. Repeat steps
Loop statements are enclosed with a second bracket. This bracket in not needed if there is only one statement.

for (
  <initial statement(s)>;
  <Condition expression>;
  <Repeat step(s)>
  )
{
  <Loop statement(s)>;
}

For loop Diagram

For loop - Examples

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

for (int i = 0, j = 2; i < 10; i++, j += 2)
{
  printf("2 x %d = %d\n", i + 1, j);
}

for (; ;)
{
  printf("I am infinite loop\n");
  delay(1000);
}

While Loop syntax

While loop stars with "while" keyword and is one condition for the loop which is enclosed within a first bracket. Loop statements are enclosed with a second bracket. This bracket in not needed if there is only one statement.

while (<Condition expression>)
{
  <Loop statement(s)>;
}

While loop Diagram

While loop - Examples

int i = 0;
while(< 10)
{
  printf("Iteration %d\n", i);
  i++;
}

while (TRUE)
{
  printf("I am infinite loop\n");
  delay(1000);
}

Do-While Loop syntax

Do While loop stars with no condition and loop statements are enclosed with second bracket. However "while" keyword along with the condition is placed at the end of the loop statement. Thus entry to the loop is unconditional but the exit or the continuation is decided by the condition expression.

do
{
  <Loop statement(s)>;

}while (<Condition expression>);

Do-While loop Diagram

Do-While loop - Examples

int i = 0;
do
{
  printf("Iteration %d\n", i);
  i++;
} while (< 10);

do
{
  printf("I am infinite loop\n");
  delay(1000);
}while (TRUE)

Important notes

Initial statement(s) - these are one or multiple statements (use comma in between). Often contains initialization of counter variables.

Repeat step(s) - these are one or multiple statements. Often contains counter operation on variables like increment, decrement etc.

Condition statement - is however only one condition statement.

Condition statement - for loop will be an infinite if it is blank.

Condition expression - while/do-while loop will be an infinite if it is a always TRUE.

Loop statement(s) - these statements are tasks in each steps. Counter variables are often used in the steps.

About our authors: Team EQA

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

#