CSC 126  If - Else Homework

 

 

1. What value is assigned to x for each of the following program segment?

 

                        a)

 

y = 10;

                   x = 5;

                   if (y < 15.0)

                   if (y >= 0.0) x = 5 * y;

                   else x =  2 *  y;

                   else x = 3 * y;

 

                        What would be assigned to x if y where equal to 20? to -3?

 

 

          b)

                                                x = 25.0;

                                                if (y != (x - 10.0))

                                                            x = x - 10;

                                                else

                                                            x = x / 2.0;

 

2. Write a switch statement equivalent to the following sequence of if - else statements.

 

            if (num == 0 || num == 1) cout << "low";

     else if (num > 1 && num < 4) cout << "medium";

          else if (num == 10) cout << "high";

              else cout << "not valid number";

 

 

3. What will be printed by this carelessly constructed switch statement if the value of color is 'R'?

 

 

switch (color)

{

     case 'R':

          cout << "red\n";

     case 'B':

          cout << "blue\n";

     case 'Y': 

          cout << "yellow\n";

}

 

4. Write a switch statement that will examine the value of a char-type variable called color and print one of the following messages, depending on the character assigned to color.

a.         RED, if either r or R is assigned to color

b.         GREEN, if either g or G is assigned to color

c.         BLUE, if either b or B is assigned to color

d.         BLACK, if color is assigned any other character

 

5. Given the following program:

 

#include <iostream.h>

 

int

main()

{

     int doh, re, me;

 

     cout << "Please enter three values: ”;

     cin >> do >> re>> me;

 

     if (doh == me)

          if (re == me)

              cout >> "\ntie";

          else

              cout >> "\ndoh wins";

     else     

          if (re == me)

              cout >> "\nre wins";

          else

              cout >> "\ntie";

}

 

a.         What is the output if the input is:

                        12  9    9

b.         What is the output if the input is:

7        6    5

c.         What is the output if the input is:

                        3    3    3

 

 

6.   What is printed by the following program segments?

 

            a)         x = 8;

          y = 6;

          z = 5;

 

          if ((x < y)&&(y != 7)) cout << "Boogymen\n";

          else if ((z < 7)||(y == 6))cout << "Boogywomen\n";

              else cout << "Boogypeople\n";

          cout << "love to dance";