C Programming
The second kind of loop structure available in C is the While Loop. Although at first glance this structure seems to be simpler than the for loop, it actually uses the same elements, but they are distributed throughout the program.
Let's try to compare the operations of for loop with while loop. The following program uses a while loop to produce the operation of our earlier for loop program, which printed the numbers from 0 to 9.
Program
void main ( )
{
int num=0; // initialization
while( num< 10) // test
{
num++; // increment
printf("The Number is %d\n",num); // statementws
}
}
Output
The Number is 0
The Number is 1
The Number is 2
The Number is 3
The Number is 4
The Number is 5
The Number is 6
The Number is 7
The Number is 8
The Number is 9
The unexpected Condition
The While loop is suited where a loop may be terminated unexpectedly by conditions developing within the loop.Consider the following program:
Program
void main ( )
{
int count=0;
printf)" Type in a phrase:\n");
while( getche( ) != ' \r ' )
count++;
printf("\n Chracter count is %d", count);
}
Output
Type in phrase:
boy
Character count is 3
The loop in this program terminates when the character typed at the keyboard is the [Return] key.
Lets look closely at the loop expression in the while loop:
while( getche( ) != ' \r ' )
This incorporates the function getche( ), returns the value of a character the instant the character is typed. As this function takes on or returns the value of the character typed so the function can be treated like a variable.

No comments:
Post a Comment