Lab #5


Objective: To practice using if statements.

  1. Write a program which reads 3 integers, prints them, and tests them, using nested conditionals, as indicated by the following program sketch.

    if (num1 is greater than 1)
       if (num2 is less than 2)
          print the letter A
       else
          print the letter B
    else 
        if (num3 is equal to 3)
           print the letter C
        else
           print the letter D
    
    Write the (compound) conditions that lead to each of the four possibles outputs.

    Run the program several times, carefully choosing values for the variables num1, num2, and num3 that will result in each output value (A, B, C, D) appearing at least once. For each of the four possible outputs, give the values you chose for num1, num2, and num3.

  2. Modify your program so that it uses a series of (unnested) if statements rather than a nested if structure. Be sure that none of the if statements contain an else clause. Test your program with the same input values as you used above to verify that its correctness.

  3. Are the conditions used in the program from question #2 mutually exclusive? If they are mutually-exclusive, is the program from question #1 more or less efficient than that from question #2 and why? If they are not mutually-exclusive, explain why not?

  4. Modify your program again so that it has the same results as for questions #1 and #2, but replace the (unnested) series of if statements with an if-else statement. Develop your conditions in a way that makes them as efficient as possible--not all of the conditions need to be compound. Test your program with the same input values as you used above to verify that it is correct.

  5. Is the if-else structure from question #4 more efficient than the series of (unnested) if statements from question #2? Explain your answer.

  6. Is the if-else structure from question #4 more efficient than the nested if structure from question #1? Explain your answer.

  7. Write a program that outputs the maximum of three integers. Use nested ifs or an if-else statement.


Return Home