while loop in C

The while statement provides an iterative loop. statement is executed repeatedly as long as expression is true. The test on expression takes place before each execution of statement.

Syntax
while (expression) {
    //statement (code to be executed)
}

As with the if-else statement, the while loop can execute multiple statements as a block by enclosing them in braces.

Flowchart of while loop in C

flowchart of c while loop

Example of the while loop in C language

Let's see the simple program of while loop that prints table of 1.

snippet
#include<stdio.h>
int main() {
    int i = 1;
    while (i <= 10) {
        printf("%d \n", i);
        i++;
    }
    return 0;
}
Output
1 2 3 4 5 6 7 8 9 10

Program to print table for the given number using while loop in C

snippet
#include<stdio.h>
int main() {
    int i = 1, number = 0, b = 9;
    printf("Enter a number: ");
    scanf("%d", & amp; number);
    while (i <= 10) {
        printf("%d \n", (number * i));
        i++;
    }
    return 0;
}
Output
Enter a number: 50 50 100 150 200 250 300 350 400 450 500
Output
Enter a number: 100 100 200 300 400 500 600 700 800 900 1000

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.

Example 1

snippet
#include<stdio.h>
void main ()
{
	int j = 1;
	while(j+=2,j<=10)
	{
		printf("%d ",j); 
	}
	printf("%d",j);
}

Output

Output
3 5 7 9 11

Example 2

snippet
#include<stdio.h>
void main ()
{
	while()
	{
		printf("hello rookienerd"); 
	}
}

Output

Output
compile time error: while loop can't be empty

Example 3

snippet
#include<stdio.h>
void main ()
{
	int x = 10, y = 2;
	while(x+y-1)
	{
		printf("%d %d",x--,y--);
	}
}

Output

Output
infinite loop

Infinitive while loop in C

If the expression passed in while loop results in any non-zero value or when always evaluates to true then the loop will run the infinite number of times.

snippet
while(1){
//statement
}
snippet
while(true){
//statement
}
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +