Demo While Loop Fragments

// To print a horizontal row of 50 asterisks: 
(remember that there are many ways of accomplishing this task)
int number = 0; 
while (number < 50)
{
     cout << "*"; number++;
}
cout<<"\n Here are "<<number <<" stars";
int number = 1;
while (number <= 50)
{
     cout << "*"; number++;
}
cout<<"\nHere are "<<number<< " stars";

 

// To print the numbers 4 - 14 on a single line: 
int num = 4;
while (num < 15)
{
      cout << num++ << " ";
 }
int num = 4; 
while (num <=14)
{
     cout << num++ << " ";

 

// Program quits when a -1 is entered:
 
(using a specified number to terminate a situation is called using a "sentinel" value)
(Notice that the first cin statement is needed to "prime" the while loop.)
int count = 0;
int grade;

cout << "Please enter grade ( enter -1 to quit)"; 
cin >> grade;

while (grade != -1) 
{
     count++;
     cout << "Grade # " << count << " is " << grade << endl;

     cout << "Please enter grade ( enter -1 to quit) ";
     cin >> grade;
}

 

Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use