.obsidian
.stfolder
IT
education
calculus
computer engineering
ECE1400
(not) Chapter 11 Exercises.md
C.md
Chapter 11 Exercises.md
Chapter 12 Exercises.md
Chapter 13 Exercises.md
Chapter 14 Exercises.md
Chapter 15 Exercises.md
Chapter 16 Exercises.md
Chapter 17 Exercises.md
Chapter 2 Exercises.md
Chapter 3 Exercises.md
Chapter 4 Exercises.md
Chapter 5 Exercises.md
Chapter 6 Exercises.md
Chapter 7 Exercises.md
Chapter 8 Exercises.md
Chapter 9 Exercises.md
Flowcharts and Pseudocode.md
ECE1410
ECE2700
english
Ohm's Law.md
math
nutrition
statistics
notes
personal
software
..gitignore.un~
.gitignore
.gitignore~
2.0 KiB
2.0 KiB
- 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)
double triangle_area(double base, height)
double product;
{
product = base * height;
return product / 2;
}
Answer:
// 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;
}
- Write a function
check(x, y, n)that returns1if bothxandyfall between zero andn - 1inclusive. The function should return 0 otherwise. Assume thatx,y, andnare all of type int
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;
}
- Suppose that function
fhas the following definition:int f(int a, int b) { ... }Which of the following statements are legal? Assume thatihas typeintandxhas typedouble).
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.
- 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.
- What will be the output of the following program?
#include <stdio.h>
void swap (int a, int b);
int main(void)
{
int i = 1, j = 2;
swap(i, j);
printf("i = %d, j = %d\n", i, j);
return 0;
}
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
Answer:
i = 1, j = 2
Because function parameters are passed by value and not reference in C, modifications to a and b are limited to the scope of swap.