The while loop in C language is used to execute a block of code several times until the given condition is true. The while loop is mainly used to perform repetitive tasks. Unlike for loop, it doesn’t contains any initialization and update statements.
Syntax of while Loop
while(condition) { /* code to be executed */ statement(s); }
While Loop Syntax Description
- condition
Condition expression is evaluated before code block of while loop. It is a boolean expression which decides whether to go inside the loop or terminate while loop. if condition expression evaluates to true, the code block inside while loop gets executed otherwise it will terminate while loop and control goes to the next statement after the while loop. - statement
While loop can contain any number of statements including zero statements.
Control flow of while Loop Statement
- While loop evaluate the condition expression. If the value of condition expression is true then code block of while loop(statements inside {} braces) will be executed otherwise the loop will be terminated.
- While loop iteration continues unless condition expression becomes false or while look gets terminated using break statement.
C Program to find sum of integers from 1 to N using while Loop
#include<stdio.h> #include<conio.h> int main(){ /* * Using while loop to find the sum * of all integers from 1 to N. */ int N, counter, sum=0; printf("Enter a positive number\n"); scanf("%d", &N); /* * Initializing loop control variable before while loop */ counter = 1; while(counter <= N){ sum+= counter; /* Incrementing loop control variable */ counter++; } printf("Sum of Integers from 1 to %d = %d", N, sum); getch(); return(0); }
Above program find sum of all integers from 1 to N, using while loop.
Output
Enter a positive number 9 Sum of Integers from 1 to 9 = 45
While Loop Interesting Facts
- The condition_expression in while loop is a boolean expression. It must evaluate to true or false value(In C, all non-zero and non-null values are considered as true and zero and null value is considered as false).
- Unlike for loop, initialization statements, condition expression and update statements are on different line.
- Opening and Closing braces are not required for single statement inside while loop code block.
For Example:
while(i < 100)
sum+= i; - We can also use infinite while loops like while(1), which will never terminate. You should add terminating condition using break statement in order to terminate infinite while loop.
For Example:
while(1) {
if(…..){
break;
}
}