You are here:   ArielOrtiz.com > Problem Solving with Programming > Exercises 1

Exercises 1

NOTE: This is a class activity, nothing needs to be delivered.

  1. Write a function called sign(n) that takes a numeric value n. It returns -1 if n is negative, 1 if n is positive greater than zero, or 0 if n is zero.
  2. The BMI (body mass index) is used to determine if a person's weight and height proportion is adequate. The BMI may be calculated using the following formula:

    index = (weight) ÷ (height2)

    Where weight should be given in kilograms and height in meters. The following table shows how different index ranges are classified:

    index range Description
    index < 20 'underweight'
    20 ≤ index < 25 'normal'
    25 ≤ index < 30 'obese1'
    30 ≤ index < 40 'obese2'
    40 ≤ index 'obese3'

    Write a function called bmi(weight, height). It should return a string that represents the corresponding BMI description computed from its input.

  3. The following algorithm can be used to determine if a certain year is a leap year:

    — Leap years are any year that can be evenly divided 
      by 4 (such as 2012, 2016, etc).
        — Except if it can can be evenly divided by 100, 
          then it isn't (such as 2100, 2200, etc).
            — Except if it can be evenly divided by 400,
              then it is (such as 2000, 2400).
    

    Write a function leap(y) that returns True if y is a leap year, otherwise returns False.

  4. Write a function next_day(y, m, d) that given a date with a certain year y, month m, and day d, returns the date of the following day.

    >>> next_day(2015, 2, 13)
    (2015, 2, 14)
    >>> next_day(2015, 2, 28)
    (2015, 3, 1)
    >>> next_day(2016, 2, 28)
    (2016, 2, 29)
    >>> next_day(2016, 12, 31)
    (2017, 1, 1)
    
  5. Write a program that asks the user for a number of cents and computes the number of dollars (100¢), quarters (25¢), dimes (10¢), nickels (5¢), and pennies (1¢) needed to make that amount, using the largest denomination whenever possible.

    For example, 247 cents is 2 dollars, 1 quarter, 2 dimes, and 2 pennies. Use // when you intend to use integer division. You do not need to write any functions other than main().

  6. Write the function intlog2(n) that returns the largest integer k such that 2kn. For example, intlog2(20) = 4 because 24= 16 is the largest power of 2 less than or equal to 20, and intlog2(32) = 5 because 25 = 32 is the largest power of 2 less than or equal to 32. Do not use any library functions inside your intlog2().