Control flow
loops

Winter 2019

charlie mcdowell

if ... else ...

 

if (boolean expresion)

      stmt 

else

      stmt

 

while ... 

 

while (boolean expression)

      stmt 

 

do ... while

do 

      stmt 

while (boolean expression);

Average - pseudocode - no while

1. Get a number.

2. If the number is 0 go to step 6.

3. Add the number to the running total.

4. Increment the count of numbers read in.

5. Go back to step 1.

6. Divide the running total by the count of number in

        order to get the average.

7. Print the average.

Average - pseudocode - using while

Get a number.

While the number is not 0 do the following:

   Add the number to the running total.

   Increment the count of numbers read in.

   Get a number.

(when the loop exits)

Divide the running total by the count of number in order to get the average.

Print the average.

General form of a while loop

InitializationStatement

while ( BooleanExpression ) {

    Statement1

    Statement2

    …

    PrepareForNextIteration

}

for ...

 

for (initial stmt; end condition; increment stmt)

      stmt 

 

Plot Values

Write a program that draws a histogram turned sideways (bar chart) by reading the values from the console and printing rows of asterisks. The number of * in each row is determined by the corresponding number from the input. For example if I enter 10 15 20 5, it should print:

**********

***************

********************

*****

A. I can do this in a few minutes.

B. I can do this but it may take more than just a few minutes.

C. I’m not sure where to start.

Switch ... case ...

switch (expression){

      case option1:

           stmt;

           break; 

      case option2:

           stmt; 

           break;

     default:

          stmt;

}

 

if (dayOfWeek == 1)

      System.out.println("Sunday");

    else if (dayOfWeek == 2)

      System.out.println("Monday");

    else if (dayOfWeek == 3)

      System.out.println("Tuesday");

    else if (dayOfWeek == 4)

      System.out.println("Wednesday");

    else if (dayOfWeek == 5)

      System.out.println("Thursday");

    else if (dayOfWeek == 6)

      System.out.println("Friday");

    else if (dayOfWeek == 7)

      System.out.println("Saturday");

    else

      System.out.println("Not a day number " + dayOfWeek);

switch (dayOfWeek) {

      case 1:

        System.out.println("Sunday");

        break;

      case 2:

        System.out.println("Monday");

        break;

      // cases 3-6 omitted to make fit on one slide

      case 7:

        System.out.println("Saturday");

        break;

      default:

        System.out.println("Not a day number " + dayOfWeek);

        break;

    }

Copy of CMPS12A - loops

By Narges Norouzi

Copy of CMPS12A - loops

  • 53