The while statement (Iteration statement) executes a statement or block of statements until the given condition is true.
Syntax:
while ( controlling expression )
{
//while loop body
}
Note: Curly Braces is optional for single statement.
Flow-chart of while loop in C
In the while loop, evaluation of the controlling expression takes place before each execution of the loop body.
How does the while loop work?
Step 1. The while loop evaluates the controlling expression.
Step 2. If the controlling expression is false, the body of the while statement is never executed, and control skips the while statement and jumps to the next statement in the program.
Step 3. If the controlling expression is true or any non zero value, then control jump within the body of while loop and execute the statements in a sequential way. Might be there is only a single statement attached with a while loop.
Step 4. After the execution of while loop statements, the process is repeated from step 1.
For example,
If you want to print a message “hello aticleworld” 6 times then while loop is your friend and it avoids writing the code 6 times for printing the message.
#include <stdio.h> int main() { int counter = 0; while(counter < 6) //controlling expression { printf(" Hello Aticleworld \n"); ++counter; //increment counter variable } return 0; }
Output:
How the above program works:
Step 1: First check while loop condition. The initial value of the counter is zero so the condition is true.
Step 2: Print the message “Hello Aticleworld” and increment the value of the counter by 1.
Step 3: After executing the while loop body, repeat the step1 and step2 until the value of the loop is less than 6.
We can terminate the while loop using the break, goto, or return keyword within the while loop body. We can also terminate an iteration without exiting the while loop using the continue keyword.
#include<stdio.h> int main() { int counter = 0; while(counter < 5 ) { if(counter == 2) { break; // terminate loop } printf("Value of counter = %d\n", counter); ++counter; } return 0; }
Output:
Value of loop = 0
Value of loop = 1
Recommended Articles for you:
- How to use if condition in C?
- How to use C if-else condition?
- How to use for loop in C?
- You should know while loop use.
- When we should use do while in the C program.
- Use of the switch case in the C program.
- C language character set.
- Elements of C Language.
- Data type in C language.
- Operators with Precedence and Associativity.
- How to pass an array as a parameter?
- Memory Layout in C.
- File handling in C, In a few hours.
- Replacing nested switches with the multi-dimensional array
- How to access a two-dimensional array using pointers?
- Brief Introduction of switch case in C.
- 100 C interview Questions.
- Function pointer in c, a detailed guide.
- How to use the structure of function pointer in c language?
- Function pointer in structure.
- Pointer Arithmetic in C.
- Brief Introduction of void pointer in C.