2.6 Review Exercises


Exercise 2.6

  1. Evaluate.
    1. 3 * (16 - 8 / 2)
    2. 24 div 8 mod 5
    3. 2 - (3 - (4 - 5))
    4. 5 ** 4
    1. -15 div 4
    2. 4 * 8 div 3
    3. 1 / 2 / 3
    4. 81 ** (1 / 2)
  2. Each of the following expressions are intended to evaluate the expression .
    Some are correct and some are not. Classify each as being correct or incorrect. For those that are incorrect, give the reason(s).
    1. (a * x ** 2 + b) / ((c * x + d)
    2. (a * x ** 2 + b) / (c * x + d)
    3. ((a)(x)(x) + b) / ((c)(x) + d)
    4. (a) * (x * x + (b) / ((c) * (x) + d)
    5. ((a * x) ** 2 + b) / c * x + d
    6. (b + x * (x * (a))) / (d + x * (c))
  3. To switch the values contained in the variables x and y, a programmer wrote the following fragment:

    x := y
    y := x

    1. If, before execution of the fragment, x had the value 7 and y had the value 3, what values would each have after the fragment was executed?
    2. Rewrite the fragment so that it performs the intended task correctly.
  4. Write a program that asks the user for a three-digit positive integer and then finds and prints the sum of the digits of the number.
  5. Write statements that will make the int variable number take on a random value distributed over the given set.
    1. {1, 2, 3, ..., 10000}
    2. {-10, -8, -6, .., 10}
    3. {50, 55, 60, ..., 200}
  6. Write a program that will pick a random number between 1 and 1000. Print the number and a message stating whether the number is an odd number or an even number.
  7. What output will be produced by each program?
    1. var x : int := 40
      
      loop
         exit when x <= 0
         put x, " " ..
         x := x - 7
      end loop 
    2. var x : int := 1
      
      loop
         x := x + 5
         put x, " " ..
         exit when x > 26
      end loop 
  8. Over the past one hundred and fifty years the population of Canada has been increasing at an average rate of 5.5% each year. Assuming that the population was 24 000 000 in 1980, write a program that finds and prints the year in which the population will reach 100 000 000, if the past growth pattern continues.
  9. Write a program to read a natural number and then find and print all of its exact divisors.