While Loop in C

Advertisements

Looping Statement in C For Loop in C

While Loop in C

In while loop First check the condition if condition is true then control goes inside the loop body other wise goes outside the body. while loop will be repeats in clock wise direction.

while loop in c

Execution Flow of While Loop

while loop in c

Syntax While Loop

Assignment;
while(condition)
{
statements;
............
Increment or Decrements (++ or --);
}

Note: If while loop condition never false then loop become infinite loop.

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.
When the condition becomes false, the program control passes to the line immediately following the loop.

When while loop is use ?

When we do not know about how many times loops are perform or iteration of loop is unknown.

Flow Diagram

while loop in c

Example of while Loop

#include<stdio.h>
#include<conio.h>

void main()
{
int i;
clrscr();
i=1;
while(i<5)
{
printf("\n%d",i);
i++;
}
getch();
}

Output

Output:
1
2
3
4

Execution process of while loop is slower than for loop.

Infinite While Loop

Example of Infinite while Loop

#include<stdio.h>
#include<conio.h>

void main()
{
  int var = 6;
  while (var >=5)
   {
    printf("%d", var);
    var++;
   }
getch();
}

Output

var will always have value >=5 so the loop would never end.

Properties of While Loop

  • In while loop onditional 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.

While Loop Can't be Empty

Example of Empty while Loop

#include<stdio.h>
#include<conio.h>

void main()
{
while()  
    {  
     printf("Hello World!");   
    }  
getch();
}

Output

compile time error: while loop can't be empty

Looping Statement in C For Loop in C

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements