While Loop Statement

A loop statement allows you to execute a statement or block of statements repeatedly. The while loop is used when you want to execute a block of statements repeatedly with checked condition before making an iteration. Here is syntax of while loop statement:

while (expression) {
// statements
}

This loop executes as long as the given logical expression between parentheses afterwhile is true. When expression is false, execution continues with the statement following the loop block. The expression is checked at the beginning of the loop, so if it is initially false, the loop statement block will not be executed at all. And it is necessary to update loop conditions in loop body to avoid loop forever. If you want to escape loop body when a certain condition meet, you can use break statement
Here is a while loop statement demonstration program:

#include <stdio.h>

void main(){
int x = 10;
int i = 0;

// using while loop statement
while(i < x){
i++;
printf("%d\n",i);
}


// when number 5 found, escape loop body
int numberFound= 5;
int j = 1;
while(j < x){
if(j == numberFound){
printf("number found\n");
break;
}
printf("%d...keep finding\n",j);
j++;
}

}

And here is the output:
1
2
3
4
5
6
7
8
9
10
1...keep finding
2...keep finding
3...keep finding
4...keep finding
number found

source:http://cprogramminglanguage.net/c-while-loop-statement.aspx

No comments:

Post a Comment