Chapter 2 Exercise Set 1


Write a function called abs, which returns the absolute value of the number it is given as its argument. The absolute value of a negative number is the positive version of that same number, and the absolute value of a positive number (or zero) is that number itself.

makeQuestion(oprd1, oprd2, op)

Write a function named makeQuestion, that takes three arguments: two operands and an operator, and returns a string with the question “What is [oprd1] [opr] [oprd2]?”.


makeQuestion(5, 7, '+');
makeQuestion(8, 2, '*');
makeQuestion(8, 2, '-');

The first call will return the string "What is 5 + 7?". The second call returns "What is 8 * 2?", and the third returns "What is 8 - 2?".

randomInt(low, high)

Write a function, randomInt(low, high), that returns a random integer between low and high inclusive.


This is essentially a rewrite of the Random between low and high exercise that you completed last chapter.

What is oprd1 + oprd2?

Rewrite the program you made in What’s 2 + 2? last chapter using the makeQuestion and randomInt functions you wrote in the exercises above. At this point you can assume that op is always +.

evaluateExpression(oprd1, oprd2, op)

Write a function named evaluateExpression, that takes three arguments: two operands and an operator, and returns the number that results from applying the operator to the opperands.


evaluateExpression(5, 7, '+');
evaluateExpression(8, 2, '*');
evaluateExpression(8, 2, '-');
evaluateExpression(10, 2, '/');

These three class to evaluateExpression will return 12, 16, 6, and 5, respectively.


You will need to use a multiway branch that matches op and applies the proper opperation to oprd1 and oprd2 accordingly.


Write a function named randomOp that randomly returns either "+", "-", "*", or "/".


Use the randomInt function you wrote earlier to generate a random number between 1 and the number of operators. Then use a multiway branch returning a different operator for each number.

What is oprd1 [+ | - | * | /] oprd2?

Use the evaluateExpression and randomOp functions you wrote in the preceding exercises to enhance the program you wrote in What is oprd1 + oprd2? so that it generates questions with random operators as well as random operands.

splitCheck(amt, numPeople, tip)

Write a function named splitCheck that takes three arguments: the total amount of the check, the number of people splitting the check, and the percent tip to be included, and returns the amount that each person needs to leave for the check.

splitCheck on the dollar

Modify splitCheck so that it rounds each person’s amount up to the nearest whole dollar.


Write a function greaterThan, which takes one argument, a number, and returns a function that represents a test. When this returned function is called with a single number as argument, it returns a boolean: true if the given number is greater than the number that was used to create the test function, and false otherwise.