Thursday, January 20, 2011

8.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:
1while (expression) {
2  // statements
3}
This loop executes as long as the given logical expression between parentheses after while 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:
01#include <stdio.h>
02  
03void main(){
04    int x = 10;
05    int i = 0;
06  
07    // using while loop statement
08    while(i < x){
09        i++;
10        printf("%d\n",i);
11    }
12  
13     
14    // when number 5 found, escape loop body
15    int numberFound= 5;
16    int j = 1;
17    while(j < x){
18        if(j == numberFound){
19            printf("number found\n");
20            break;
21        }
22        printf("%d...keep finding\n",j);
23        j++;
24    }
25     
26}
And here is the output:
1
2
4
3
5
8
6
7
9
.k
10
1.
.eep finding
2...keep finding
3...keep finding
number found
4...keep finding

Dont Miss Another Post Connect With Us !

Enter your email address:

0 comments: