CS16, 10S, Handout to go with H04 (Simple function definitions) (printable PDF)
Available online at: http://www.cs.ucsb.edu/~pconrad/cs16/10S/homework/H04/handout
The assignment is available at http://www.cs.ucsb.edu/~pconrad/cs16/10S/homework/H04

This handout is your reading assignment to go with H04.


Homework H04 involves writing simple function definitions. Here are some example solved problems you can use as models.

Question: Write a function definition for a function called xSquared that takes an integer x as its parameter, and returns an integer value x2 (or x times x).

Answer:

int xSquared(int x)
{
  return x*x;
}

Here's some more detail:


Continued from other side

Here's another example:

Question: Write a function definition for a function called xCubed that takes a real number x as its parameter, and returns a real number value x3 (or x times x times x).

Answer:

double xCubed(double x)
{
  return x*x*x;
}

The differences here are:

 

One last example—this one has two parameters:

Question: Write a function definition for a function called perimeterOfRectangle that takes real numbers w and h as parameters (which stand for width and height), and returns the perimeter of the rectangle as a real number. The formula is p = 2w + 2h

Answer:

double perimeterOfRectangle(double w, double h)
{
  return 2*w + 2*h;
}

Note here that:

With those examples, you should be able to complete homework H04.


End of H04 handout