Homework Assignment 2 Solutions

Solutions:
  1. Modulus.C: Write a program that inputs i and j and prints out i%j.
    Solution

  2. CalcArea.C: Write a program that inputs a, b, c and d, integer dimensions in the following diagram, and prints out the area of the figure.
    
                            c
                         +-----+
                         |     |
                         |     |
                       b |     |
                         |     |
                 a       |     |  d
           +-------------+     |
           |                   |
           |                   |
           +-------------------+
    
    

    Solution

  3. FencePost.C: A fence runs along an infinite line, with fence posts at integer locations. That is, there are posts at location 3, 4, 5, and so on. Given locations i and j, with j larger than i, how many posts are included between i and j, including i and j.
    Solution

  4. NChooseThree.C: Write a program which inputs integer n and outputs the integer n (n+1) (n+2) / 3. By changing the parentheses, show how three different answers are possible for a given n.
    Solution

  5. NChooseTwo.C: A stair-step figure of size n is built up of 1-by-1 tiles. Write a programing which calculates and prints the total area of the figure for a given n. We show by example how the figure's shape depends on n. For n=3 the figure looks like:
                      +---+
                      |   |
                  +---+   |
                  |       |
              +---+       |
              |           |
              +-----------+
    
    for n=4 the figure looks like:
                          +---+
                          |   |
                      +---+   |
                      |       |
                  +---+       |
                  |           |
              +---+           |
              |               |
              +---------------+
    

    Solution