.

     
MathBits.com
     Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use                                                                                      
                                                              
Do...While Demo Fragments

// To print the message HAPPY BIRTHDAY 10 times;
int counter = 0;

do
{
     System.out.println( "HAPPY BIRTHDAY! ");
     counter++;
}
while (counter <10);




// To add a total, count, and average grades:
double total = 0;                 // be sure to initialize variables to zero to avoid
int counter = 0;           // allowing the computer to use it's "garbage".
double average = 0;
int grade;                   // Why is this variable not set equal to zero? It is filled by user.

do
{
     grade=Console.readInt("Enter the grade scored.\n Enter -999 to quit. ");
    
     if (grade != -999)                // separating sections of the program 
     {                                            // by inserting an empty line helps organize
             total += grade;           // your thinking and allows for easy reading.
             counter++;
      }

}
while (grade != -999);

average = total / counter;

System.out.println("The average of your " + counter + " grades is "+ average +".");

                                 
 

                     
Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use