C – while Loop Statement
In a programming language, a loop is useful for running iterative tasks. Using a loop a program can execute code block for multiple times as required.
Mainly there are 3 types of loops available in C programming language. Where while loop is one of them. Below is the list if loop available.
- for loop
- while loop
- do-while loop
while Loop
While loop is also an entry-restricted loop. Where a condition is checked before executing the code block.
If the condition evaluates to true, the block of code is executed and if the condition evaluates to false loop is terminated and control goes to just after the loop body.
Syntax:
1 2 3 4 | while ( condition ) { // code block } |
while Loop Working
- Step 1 – Loop start
- Step 2 – The conditions are checked. If the condition evaluates to false go to step 4. If the condition evaluates to true then continue to step 3.
- Step 3 – Code block is executed and goto Step 2.
- Step 4 – Exit loop
while Loop Example
A sample C programme to calculate the sum of 1 to 100 numbers using while loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // C Program to calculate the sum of 1 to 100 numbers #include <stdio.h> int main() { int i, sum = 0; i = 1; while(i <= 100) { sum += i; i++; } printf("Sum of 1-100 is %d", sum); return 0; } |
Output:
Sum of 1-100 is 5050