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:
int
, because the instructions say it should return an integer value. On this assignment, your function definitions will always start with either int
(if they are supposed to return a value that is an integer), or double
(if they are supposed to return a value that is a real number that may have decimals.)Please turn over for more
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:
()
we have (double x)
instead of (int x)
double
as the word in front of the name of the function.
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:
double w, double h
2*w + 2*h
With those examples, you should be able to complete homework H04.