JavaScript, Lesson 6 - Homework

JavaScript, Lesson 6 - Homework

Q1

Here is a program that defines and calls a function. However, the program is full of errors. Please correct all the errors:

<script language=JavaScript">
function my Function ();
var x;
x = 2;
document.write("The value of x is " + x);
};

document.write("Here I call the function : " + myfunction)
<\script>

Q2

In the following program, what number is displayed on the screen?

<script language="JavaScript">
alert(func(func(2,3),func(3,2)));

function func (x, y)
{ return 10 * x + y;
}
</script>
Type your answer here:

Q3

Write a function which takes three parameters, called first, second and third, and which returns the largest of the three parameters.

Q4

Look at this program:

<script language="JavaScript">
function multiply (x, y)
{ return x * y;
}

var y = 12.5, x = 9.5;
document.write(multiply(y, x));
</script>

What are the values of x and y before the function is called? x = y =
What are the values of x and y inside the function? x = y =
What is the value is displayed by the program?

Q5

Write three functions, add to add the its two parameters together and return the sum, multiply to multiply its two parameters, and square to multiply its single parameter by itself (i.e. if the parameter were 3, the result would be 9, if it were 7, the result would be 49 etc.)

Use your functions to calculate the result of this mathematical expression, which should be calculated using four function calls:

(3*4 + 5*7)2

Q6

(This question is for those people who are familiar with mathematical notation.)

The Ackerman Function y() is defined as follows:

  • A(0,y) = y + 1
  • A(x + 1, 0) = A(x, 1)
  • A(x + 1, y + 1) = A(x, A(x + 1, y))

Write a program which implements the Ackerman function, and use it to calculate the value of A(4,3).

Q7

Consider the factorial function defined in the tutorial. What would happen if the function were called as follows? Would the function ever terminate?

  • factorial(-7)
  • factorial(2.6)

If you decide in each case that the function would terminate, what value would it produce in each case? If you decide that the function wouldn't terminate, how could you adapt the function so that it would still function correctly, but would terminate in the cases shown above?