1 of 10

While Loop �& �Do-While Loop

2 of 10

While Loop

  • while loop in C programming repeatedly executes a target statement as long as a given condition is true.
  • Syntax

while(condition)

{ statement(s); }

  • Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.

3 of 10

Properties of While loop

  • A conditional expression is used to check the condition. The statements defined inside the while loop will repeatedly execute until the given condition fails.
  • The condition will be true if it returns 0. The condition will be false if it returns any non-zero number.
  • In while loop, the condition expression is compulsory.
  • Running a while loop without a body is possible.
  • We can have more than one conditional expression in while loop.
  • If the loop body contains only one statement, then the braces are optional.

4 of 10

5 of 10

Program

#include <stdio.h>

int main()

{

int a = 10;

while( a < 20 )

{ printf("value of a: %d\n", a);

a++;

}

return(0);

}

6 of 10

Do-While Loop

  • Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming checks its condition at the bottom of the loop.
  • do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.
  • Syntax:-

do{

statement(s);

}while( condition );

7 of 10

8 of 10

Program

#include <stdio.h>

int main ()

{int a = 10;

do {

printf("value of a: %d\n", a);

a = a + 1;

}while( a < 20 );

return 0;

}

9 of 10

Difference between For & While

For Loop

While Loop

The number of iteration are Known.

The number of iteration are unknown.

A condition is in the form of relational expression.

A condition is in the form of non-zero value or expression

The initialization may exist both- outside the loop or in the loop statement.

The initialization, in this case, always occurs outside the loop.

The increment occurs only after the execution of the statement(s).

We can perform the increment both- after or before the execution of the given statement(s).

We use the for loop when the increment and initialization are very simple.

We use the while loop in the case of a complex initialization.

Syntax

Syntax

e.g

e.g

10 of 10

HOME WORK

  • Difference between

1. While & Do-While

2. For & do-While