Demo Fragments
Ending a Program or Loop Early
 

// using break within a loop                      
// eliminating the letter c                             

apstring puppy = "DipStick";                          
int count = -1;                                                  
while (count < 8)                                              
{                                                                          
       count++;
       if (puppy[count]=='c')
               break;

        cout << puppy[count] << "\n";
}                                                                          
cout<< "Isn't this puppy a cutie!!";
 
// using continue within a loop
// eliminating the letter c
apstring puppy="DipStick"; 
int count = -1; 
while (count < 8)
{
     count++;
      if ( puppy[count] =='c')
               continue; 
       
       cout << puppy[count] << "\n";
}
cout<< "Isn't this puppy a cutie!!";          
Screen display:
D
i
p
S
t
i
Isn't this puppy a cutie!!
Screen display:
D
i
p
S
t
i
k
Isn't this puppy a cutie!!



// using exit ( )
if ((age < 19) && ( grade >= 85) && (infractions == 0))
      exit(1);            // program STOPS here. Nothing else will be printed.

if (grade < 85)
      cout<< "Your grades need to improve.\n";

cout<<"You are not eligible this semester. Try again next semester.";


// using return 0
     apstring name;
     if (name != "Donald")
                return 0;               // program STOPS here. Nothing else will be printed.

         cout << "You receive a discount of 15%. \n"
                 << "Your cost is " << .85 * cost << "\n";

         return 0;
}

 

 

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