We used loops to execute a block of code several times.
Syntax of a While loop
while ( Condition ) { // body statement. }
Condition : After checking the condition it decides whether loop needs to continue or not. If the condition is false then the loop will not be executed.
Let’s look into the following program which will print “Hello world” 5 times.
#include <stdio.h> int main() { int i = 1; while ( i <= 5 ) { printf("Hello World \n"); i++; // Update. } return 0; }
Output
Hello World Hello World Hello World Hello World Hello World
How it works
Step 1 : First it will check either the condition ( i <= 5 ) is true or not. If the condition is true only then it will go to the body statement. Otherwise it will be terminated.
Step 2 : In the body statement, there is a print command and it will be executed.
Step 3 : After that, Update statement will be executed
Step 4 : Start repeating from Step 1.
No comments:
Post a Comment