68 lines
1.9 KiB
Markdown
68 lines
1.9 KiB
Markdown
> 1. The following function, which computes the area of a triangle, contains two errors. Locate the errors and show how to fix them. (*Hint*: There are no errors in the formula)
|
|
```c
|
|
double triangle_area(double base, height)
|
|
double product;
|
|
{
|
|
product = base * height;
|
|
return product / 2;
|
|
}
|
|
```
|
|
|
|
Answer:
|
|
```c
|
|
// A type annotation is needed for `height`
|
|
double triangle_area(double base, double height)
|
|
{
|
|
// The `product` variable declaration was not in the function block.
|
|
double product;
|
|
product = base * height;
|
|
return product / 2;
|
|
}
|
|
```
|
|
|
|
> 2. Write a function `check(x, y, n)` that returns `1` if both `x` and `y` fall between zero and `n - 1` inclusive. The function should return 0 otherwise. Assume that `x`, `y`, and `n` are all of type int
|
|
```c
|
|
int check(int x, int y, int n) {
|
|
int in_range = 1;
|
|
if (x < 0 || y < 0) {
|
|
in_range = 0;
|
|
}
|
|
if (x > n - 1 || y > n - 1) {
|
|
in_range = 0;
|
|
}
|
|
|
|
return in_range;
|
|
}
|
|
```
|
|
|
|
> 7. Suppose that function `f` has the following definition:
|
|
> `int f(int a, int b) { ... }`
|
|
> Which of the following statements are legal? Assume that `i` has type `int` and `x` has type `double`).
|
|
|
|
Answer:
|
|
All of them are legal and will compile and run. (c) and (d) are what I would consider bad practice because they perform an implicit conversion from a double to an int, and should include an explicit cast.
|
|
|
|
> 8. Which of the following would be valid prototypes for a function that returns nothing and has one double parameter?
|
|
|
|
Answer:
|
|
(a) and (b).
|
|
Parameters must contain a type annotation but they do not need to specify a name. A function prototype declaration must specify a return type.
|
|
|
|
> 9. What will be the output of the following program?
|
|
```c
|
|
double triangle_area(double base, double height)
|
|
{
|
|
double product;
|
|
product = base * height;
|
|
return product / 2;
|
|
}
|
|
double triangle_area(double base, double height)
|
|
{
|
|
double product;
|
|
product = base * height;
|
|
return product / 2;
|
|
}
|
|
|
|
```
|
|
|