JavaScript Worksheet

Solutions

Try to write JavaScript programs that do the following. Each build on the one before. You may use document.writeln or alert for output. Be sure to test your program after each step. Make sure it works before moving on.

Task Course Link
1

Ask the user for two numbers and output their sum.

2-25.html
2
  1. Write a function called isEven that takes one parameter n and outputs the message to the user indicating if the number is even or odd.
  2. Call the function with the sum calculated in step one as its parameters.
2-20.html (if)
2-27.html (functions)
3
  1. Write an if/else statement that determines which is larger and which is smaller.
  2. Store the larger in a variable called large and the smaller in a variable called small.
  3. Output the value stored in large.
2-20.html
4 Write a while loop that outputs the numbers from small up to large. 2-25.html
5 Modify your while loop so that it multiplies all of the numbers between small and large together and outputs the result after the loop. 2-25.html
6
  1. Write a function called formatNumber that takes one parameter n.
  2. The function should contain one document.writeln that prints n in italics followed by a line break.
  3. Comment the line from part 4 that output the number and replace it with a call to the function formatNumber.
2-27.html
7
  1. Write a function called hypotenuse which calculates and returns the hypotenuse of a right triangle. (c from the Pythagorean theorem : a^2 + b^2 = c^2).
  2. Use the parameters side1 and side2.
  3. JavaScript does not have an exponent operator (^ does something else).
  4. Use the built in square root function: Math.sqrt.
  5. Return the value with a return statement. This function contains NO output statements.
  6. Call the function from your main script with the parameters small and large and output the result.
2-27.html
Challenge This problem is beyond what we cover in this class, but if you are looking for a challenge...
  1. Write a JavaScript function to format an HTML table cell (<td> tags) that displays a number, and somehow varies the appearance of that number if it is odd or even (different colors, underlining, bold).
  2. Use the function you have written and loops to print a multiplication table for the numbers small to large.
  3. For this you will need to nest one while loop within another.
2-27.html (tables)
2-25.html (loops)
2-27.html (functions)

Clif Presser<cpresser@gettysburg.edu>
Last modified: Tue Mar 4 09:46:42 EST 2014