CMU 15-112: Fundamentals of Programming and Computer Science
Week 1: Data and Variables



Code Tracing
What will this code print? Figure it out by hand, then run the code to confirm. Then slightly edit the code and try again.

Free Response (Problem-Solving)

  1. eggCartons(eggs)
    Write the function eggCartons(eggs) that takes a non-negative integer number of eggs, and returns the smallest integer number of cartons required to hold that many eggs, where a carton may hold up to 12 eggs.

  2. distance(x1, y1, x2, y2)
    Write the function distance(x1, y1, x2, y2) that takes four int or float values x1, y1, x2, y2 that represent the two points (x1, y1) and (x2, y2), and returns the distance between those points as a float.

  3. triangleArea(s1, s2, s3)
    Write the function triangleArea(s1, s2, s3) that takes 3 floats representing sides and returns the area of the triangle that has those lengths of its side. Assume that only legal input is provided. Hint: you will probably wish to use Heron's Formula.

  4. triangleAreaByCoordinates(x1, y1, x2, y2, x3, y3)
    Write the function triangleAreaByCoordinates(x1, y1, x2, y2, x3, y3) that takes 6 int or float values that represent the three points (x1,y1), (x2,y2), and (x3,y3), and returns as a float the area of the triangle formed by those three points. Hint: you should make constructive use of the functions you just wrote above or use the internet to find a formula. A challenge would be to try both.

  5. lineIntersection(m1, b1, m2, b2)
    Write the function lineIntersection(m1, b1, m2, b2) that takes four int or float values representing the 2 lines:
        y = m1*x + b1
        y = m2*x + b2
    This function returns the x value of the point of intersection of the two lines. Assume all the lines are intersecting at a point and not parallel or identical.

  6. nthFibonacciNumber(n)
    Background: The Fibonacci numbers are defined by F(n) = F(n-1) + F(n-2). There are different conventions on whether 0 is a Fibonacci number, and whether counting starts at n=0 or at n=1. Here, we will assume that 0 is not a Fibonacci number, and that counting starts at n= 1, so F(1)=1, and F(2)=2. With this in mind, write the function nthFibonacciNumber(n) that takes a non-negative int n and returns the nth Fibonacci number. Some test cases are provided for you. You can use Binet's Fibonacci Number Formula which (amazingly) uses the golden ratio to compute this result.

  7. Bonus : isFactor(f, n)
    Without using any conditionals, write the function isFactor(f, n) that takes two int values f and n, and returns True if f is a factor of n, and False otherwise. Note that every integer is a factor of 0.