APS105 L18 - Midterm Review
Example 1: Use pointers to get average of an array of integers.
#include <stdio.h>
double average(int numbers[], int numbersLength) {
int sum = 0;
for (int i = 0; i < numbersLength; ++i) {
// sum += numbers[i];
sum += *(numbers + i); // using pointers to add the sum
}
return (double) sum / numbersLength;
// type casting so we get a double in return instead of an int
}
int main(void) {
int numbers[] = {1, 2, 3};
int numbersLength = 3;
printf("%lf", average(numbers, numbersLength));
return 0;
}
Difference between ++i and i++:
++iandi++both add1to the variableii++doesn't return the output with1added to the variable- e.g. if you do
printf("%d", i++);, it adds1toi, but in the print statement it doesn't print out the updatedi.
- e.g. if you do
- "Unless you have a good reason not to, always prefer to use
++i" - Eyolfson
Example 2: Use arrays and pointers to get intersection of lines.
#include <stdio.h>
#include <stdbool.h>
bool linesIntersect(double m1, double b1, double m2, double b2, double *x, double *y) {
if (m1 == m2) {
return false;
}
*x = (b2 - b1) / (m1 - m2);
*y = m1 * *x + b1;
return true;
}
bool allLinesIntersect(double m[], double b[], int length, double *x, double *y) {
for (int i = 0; i < length - 1; ++i) {
if (!linesIntersect(m[i], b[i], m[i], b[i], *x, *y)) {
return false;
}
}
return true;
}
int main(void) {
double x = 0;
double y = 0;
double m1 = 1.0;
double b1 = 3.0;
double m2 = 2.0;
double b2 = 1.0;
if (linesIntersect(m1, b1, m2, b2, &x, &y)) {
printf("two lines intersect at %lf %lf", x, y);
}
return 0;
}
2020 Question 7: Check bit size of a computer
#include <stdio.h>
int main(void) {
int test = 1;
int count = 1;
while (test > 0) {
test *= 2; // this works because if you multiply by 2 enough times the result will have the sign flip
++count;
}
printf("\nsize: %d\n", count);
return 0;
}
"This was a cute question that almost no one got [...] it was kind of silly." - Eyolfson
- How nice of the teaching team! Very silly, very quirky.
- Eyolfson said this is not out of scope, just not nice to ask—awesome.
- "2020 was a bloodbath—yours is not going to be a bloodbath"
Comments are not required on the midterm!!!
"If it works it works" - Eyolfson
If your output is wrong though, comments may help your TA give you part marks.