next up previous
Next: do-while Loop Up: Overview of C++ Previous: Time Delay Loops

while Loop

For situations where your program need to loop as long as a specific condition is met, but not necessary a specific number of times, you can use while statement. The general formate of the while statement is as follows:

while(condition) statement;

or for a block as

while(condition)
{
sequence of statements

}
The condition that controls the loop can be any valid C++ expression.

Example
*/ This portion of a program can be used to ensure that user enters the correct response*/
#include <iostream.h>
main()
{
char ans; //character assignment
cout <<"Do you want to continue (Y/N)";
cin>> ans;
while((ans !='Y')&&(ans !='N'))
{
cout <<"$\backslash$n You must type a Y or an N $\backslash$n";
cout <<"Do you want to continue (Y/N)";
cin>> ans;
}
return 0;
}

Example
/* This program displays all printable characters, including the extended character set, if one exists. The unsigned char modifies and extends the char to go from 0 to 255 */

#include <iostream.h>
main()
{
unsigned char ch;
ch=1;
while(ch !=0){
cout<<ch;
ch++;
}
return 0;
}



 

Yousef Haik
2/23/1998