vault backup: 2025-01-07 18:14:44

This commit is contained in:
arc
2025-01-07 18:14:44 -07:00
parent 544cfb24fc
commit c99ca523f4
21 changed files with 10 additions and 0 deletions

View File

@ -0,0 +1,20 @@
1. Suppose that the following declarations are in effect:....
a. `14`
b. `34`
c. `4`
d. `true`
e. `false`
2. Suppose that `high`, `low`, and `middle` are all pointer variables of the same type, and the `low` and `high` point to elements of an array. Why is the following statement illegal, and how could it be fixed?
```c
middle = (low + high) / 2
```
The above statement is illegal because you can't add an `int *` to an `int *`. The below operation is legal because you can perform pointer subtraction, and because `low` is defined on the left hand side of the equation, then adding a long to a pointer is valid.
```c
middle = low + (high - low) / 2;
```
3. What will be the contents of the `a` array after the following statements are executed?
```c
{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
```

View File

@ -0,0 +1,136 @@
# Compilation Steps
1. Preprocessing: The preprocessor obeys commands that begin with #, also known as directives
Commands for the preprocessor are called directives. Directives begin with a pound sign, and they do not end with a semicolon.
Example:
```c
#include <stdio.h>
```
2. Compiling. A compiler translates then translates the program into machine instructions.
3. Linking: The generated objects are combined to create a complete executable.
The preprocessor is typically integrated with the compiler.
# Types
## Strings
A string literal is characters enclosed in double quotation marks.
A newline can be inserted using `\n`.
## Integers
An integer is a way to store a whole number. In C, integers are signed by default.
Values of an integer type are whole numbers.
Integers are divided into two categories, signed, and unsigned.
If the sign bit is zero, it's a positive value, and if it's 1, the value is negative.
They cal be declared using `[short|long] [signed|unsigned] int`, resulting in 6 possible combinations
C99 adds a `long long` int
## Floats
A float is a decimal value. Slower arithmetic and inexact values are both drawbacks of using floats.
## Characters
In C, a `char` denotes a single byte of arbitrary encoding.
## Variables
A variable must be declared before it is assigned.
## Arrays
### Finding the size of an array
```c
int arr[10];
// The size of an array can be found by
// determining the number of bytes allocated total and dividing that by the size of each element in the array.
int arr_size = sizeof(arr) / sizeof(arr[0]);
```
# Pointers
`&` gives you the address of a variable
`*` gives you the value in memory that an address points to.
To update the value a pointer points at, you can dereference on the left hand side of the assignment operator:
```c
// Update the value `p` points at to be 7
*p = 7;
```
Because of how operator precedence works, parentheses should be placed around the dereference operator and the variable
```c
// Increment the value pointed to by `p`
(*p)++;
```
# Formatting specifiers
# Standard library
## Formatting specifiers
| Specifier | Function |
| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `%d` | Decimal representation: Display a value as a base 10 (hence the decimal) integer. |
| `%f` | Fixed point decimal representation. Specify the number of places to round to by adding a decimal and a number, eg `%.2f` would round to two decimal places. |
| `%e` | Exponential floating point number representation. |
| `%g` | Either fixed point or exponential representation, whichever has a more compact representation. |
For number formatting specifiers, the convention is as follows:
`%-a.bX`
`%`: Start of the formatting specifier
`-`: (optional) If included, justify value left in space. Otherwise, justify right in space
`a`: (optional) If included, the size of the field in characters.
`.`: Separator between `a` and `b`. Optional if `b` is not specified
`b`: The number of decimal places to round to
`X`: The type of format to use, and the end of the specifier. Use `d` for integer base 10 (decimal) representation, `f` for fixed point decimal, and `e` for exponential notation, and `g` to select between fixed point and exponential, whichever is shorter.
## `printf`
Used to write a string to stdout with the ability to format variables into the string.
Write a string to standard output. `f` indicates that it's a formatting string. The string will not include move the cursor to a newline, append `\n` to the end of the string to do so.
Printf accepts a variable number of arguments, the first argument is the formatting string, then following arguments are the arguments to be inserted into the string.
TODO: examples
## `scanf`
Read value(s) from stdin.
`scanf` is to stdin as `printf` is to stdout.
The format of the input is specified using [formatting specifiers](#Formatting%20specifiers), and all following arguments are pointers pointing to variables to update.
### Examples
```c
// Read a float from standard input into the variable `v`.
float v;
// Here, `v` is uninitialized
scanf("%f", &v);
printf("You input: %f", v);
```
### Behavior
The validity of a `scanf` call is not necessarily checked at compile time, and so the number of outputs specified should match the number of inputs.
For each formatting specifier specified in the string, `scanf` will attempt to locate an appropriate value in the input, skipping whitespace and newlines if necessary until the beginning of a number is reached.
When asked to read an integer, `scanf` searches for one of:
- A digit
- A plus or minus sign
It will continue to read until it reaches a nondigit (whitespace is not skipped in this case, and it is counted as a nondigit). If it doesn't encounter a valid digit first, it will return early.
When asked to read a float, `scanf` searches for one of:
- A plus sign or minus sign
- A series of digits (possibly containing a decimal point), followed by an exponent (optional). An exponent consists of the letter `e` or `E`, an optional sign, and one or more digits.
`%e`, `%f`, and `%g` all follow the same rules for recognizing floating point numbers.
If an ordinary character is included in the pattern matching string, it will be matched then discarded before proceeding to the next character.
## `rand`
```c
// `srand` creates a seed to use for rng
srand(time(NULL));
// `rand` generates a random integer between 0 and `RAND_MAX`
// To pick a number between a particular range, you can use the modulo
// operator.
// The below example picks a number between zero and four.
int num = rand() % 4;
```

View File

@ -0,0 +1,30 @@
> 1. If `i` is a variable and `p` points to `i`, which of the following expressions are aliases for `i`?
a. `*p`
g. `*&i`
> 2. If `i` is an `int` variable and `p` and `q` are pointers to `int`, which of the following assignments are legal?
e. `p = *&q;`
f. `p = q;`
i. `*p = *q`
> 3. The following function supposedly computes the sum and average of the numbers in the array `a`, which has length `n`. `avg` and `sum` point to the variables that the function should modify, unfortunately the function contains several errors, find and correct them.
```c
void avg_sum(double a[], int n, double *avg, double *sum)
{
int i;
// This was assigning a pointer to a float,
// the dereference operator was missing
*sum = 0.0;
for (i = 0; i < n; i++)
// This wasn't increasing the value
// `sum` points to, it was modifying the address stored in the pointer
(*sum) += a[i];
// Missing dereference operators
*avg = *sum / n;
}
```

View File

@ -0,0 +1,34 @@
1. Suppose that the following declarations are in effect:....
a. `14`
b. `34`
c. `4`
d. `true`
e. `false`
2. Suppose that `high`, `low`, and `middle` are all pointer variables of the same type, and the `low` and `high` point to elements of an array. Why is the following statement illegal, and how could it be fixed?
```c
middle = (low + high) / 2
```
The above statement is illegal because you can't add an `int *` to an `int *`. The below operation is legal because you can perform pointer subtraction, and because `low` is defined on the left hand side of the equation, then adding a long to a pointer is valid.
```c
middle = low + (high - low) / 2;
```
3. What will be the contents of the `a` array after the following statements are executed?
```c
{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
```
5. Suppose that `a` is a one dimensional array and `p` is a pointer variable. assuming that the assignment `p = a` has just been performed, which of the following expressions are illegal because of mismatched types? Of the remaining expressions, which are true (have a nonzero value)?
The following expressions are illegal because of mismatched types:
- (a) `p == a[0]` - Comparison between `int *` and `int`
The rest of the expressions are true.
8. Rewrite the following function to use pointer arithmetic...
```c
void store_zeros(int *a, int n) {
for (int i = 0; i < n; i++) {
*(a + i) = 0;
}
}
```

View File

@ -0,0 +1,70 @@
> **1.** The following function calls supposedly write a single new-line character, but some are incorrect. Identify which calls don't work and explain why.
b. `printf("%c", "\n");` - This is invalid because the double quotes make `\n` a string, but it's being displayed with the `%c`formatting specifier.
c. `printf(%s, '\n');` - This is invalid because it's trying to display a `char` using the string formatting specifier.
e. `printf('\n');` - `printf`'s first argument should be a string, not a `char`.
h. `putchar("\n");` - `putchar`'s first argument should be a `char`, not a string.
i. `puts('\n');` - `puts`'s first argument should be a string, not a `char`.
j. `puts("\n");` - `puts` will write a newline after writing a string, so this will write two newlines.
---
> **2.** Suppose that `p` has been declared as follows:
```c
char *p = "abc";
```
> Which of the following function calls are legal? Show the output produced by each legal call, and explain why all the others are illegal.
```c
// A - Not legal, because putchar accepts a `char`, not a pointer.
putchar(p);
// B - Legal, output: `a`
putchar(*p);
// C - Legal, output: `abc`
puts(p)
// D - Illegal, `puts` accepts a pointer to a null terminated string, not a `char`.
```
---
> **3.** Suppose that we call `scanf` as follows:
```c
scanf("%d%s%d", &i, s, &j);
```
> If the user enters `12abc34` `56def78`, what will be the values of `i`, `s`, and `j` after the call? (Assume that `i` and `j` are `int` variables and `s` is an array of characters.)
- `i`: `12`
- `s`: `"abc34"`
- `j`: `56`
---
> **7.** Suppose that `str` is an array of three characters. Which one of the following statements is not equivalent to the other three?
```c
// A
*str = 0;
// B
str[0] = '\0';
// C
strcpy(str, "");
// D
strcat(str, "");
```
(d) is different because it effectively does nothing (concatenates `"abc"` with an empty string). The rest of them make `str` effectively empty by setting the first character to a null byte.
---
> **9.** What will be the value of the string `s1` after the following statements have been executed?
```c
// Assuming `str` is an empty string with enough space to store everything:
strcpy(str, "tire-bouchon");
// "tire-bouchon"
strcpy(&str[4], "d-or-wi");
// "tired-or-wir"
strcat(str, "red?");
// "tired-or-wired?"
```
Expected output:
```c
"tired-or-wired?"
```

View File

@ -0,0 +1,50 @@
> **12.** Suppose that the macro `M` has been defined as follows:
```c
#define M 10
```
> Which of the following tests will fail?
```c
// C will fail, because `M` is defined.
#ifndef M
// E will fail, because `M` is defined
#if !defined(M)
```
---
> **13.** Show what the following program will look like after preprocessing. You may ignore any lines added to the program as a result of including the `<stdio.h>` header.
```c
#include <stdio.h>
int main(void)
{
f();
}
void f(void) {
printf("N is %d\n", 100);
}
```
---
> **15.** Suppose that a program needs to display messages in either English, French, or Spanish. Using conditional compilation, write a program fragment that displays one of the following three messages, depending on whether or not the specified macro is defined.
```c
#ifdef ENGLISH
#define MESSAGE "Insert Disk 1"
#endif
#ifdef FRENCH
#define MESSAGE "Inserez Le Disque 1"
#endif
#ifdef SPANISH
#define MESSAGE "Inserte El Disco 1"
#endif
printf(MESSAGE);
```

View File

@ -0,0 +1,83 @@
> **1.** Section 15.1 listed several advantages of dividing a program into multiple source files.(a). Describe several other advantages
- Easier to scale horizontally as developers are added to the team
- Reduced cognitive load from less global scope to keep track of
> (b). Describe some disadvantages
- Increased complexity
- Need to maintain/troubleshoot a build system
---
> **2.** Which of the following should *not* be put in a header file? Why not?
b. Function definitions - Functions should only be defined once, and this allows multiple files to share the same function definition
---
> **3.** We saw that writing `#include <file>` instead of `#include "file"` may not work if file is one that we've written. Would there be any problem with writing `$include "file"` instead of `#include <file>` if *file* is a system header?
Yes, `""` is a path relative to the current file, whereas `<>` is a path to the system's standard library headers.
---
> **4.** Assume that `debug.h` is a header file with the following contents...
>(a). What is the output when the program is executed?
```
Output if DEBUG is defined:
Value of i: 1
Value of j: 2
Value of i + j: 3
Value of 2 * i + j - k: 1
```
> (b). What is the output if the `#define` directive is removed from `testdebug.c`?
```
Output if DEBUG is not defined:
```
> (c). Explain why the output is different in parts (a) and (b)
When `DEBUG` is defined, any instances of the `PRINT_DEBUG` token are replaced with a `printf` call during compile time, but when it's not defined, they're replaced with nothing.
> (d). Is it necessary for the `DEBUG` macro to be defined *before* `debug.h` is included in order for `PRINT_DEBUG` to have the desired effect? Justify your answer.
Macro invocations are evaluated sequentially, and so if `DEBUG` was defined after `PRINT_DEBUG`, then any usages of `PRINT_EVALUATION` would be have like `DEBUG` was not defined.
---
> **5.** Suppose that a program consists of three source files - `main.c`, `f1.c`, and `f2.c`- Plus two header files, `f1.h` and `f2.h`. All three source files include `f1.h` but only `f1.c` and `f2.c` include `f2.h`. Write a makefile for this program, assuming that the compiler is `gcc` and that the executable file is to be named `demo`.
```makefile
demo: main.o f1.o f2.o
gcc -o demo main.o f1.o f2.o
main.o: main.c f1.h
gcc -c main.c
f1.o: f1.c f1.h f2.h
gcc -c f1.c
f2.o: f2.c f2.h
gcc -c f2.c
```
---
> **6.** The following questions refer to the program described in Exercise 5.
> (a). Which files need to be compiled when the program is built for the first time?
`f1.c`, `f1.h`, `f2.c`, `f2.h`, `main.c`, `main.h`
> (b). If `f1.c` is changed after the program has been built, which files need to be recompiled?
Just `f1.c`.
> (c). If `f1.h` is changed after the program has been built, which files need to be recompiled?
All source files, because they all include `f1.h`.
> (d). If `f2.h` is changed after the program has been built, which files need to be recompiled?
`f1.c` and `f2.c`.

View File

@ -0,0 +1,21 @@
Yes they are, different structs can have the same field names.
> 2
```c
struct c1 C1 { 0.0, 1.0};
struct c1 C2 { 1.0, 1.0};
```
> 8a
```c
const struct color MAGENTA { 255, 0, 255};
```
>11
20 bytes
UNCOMPLETED

View File

@ -0,0 +1,90 @@
> **4.** Suppose that the following declarations are in effect:
```c
struct point {int x, y; };
struct rectangle { struct point upper_left, lower_right; };
struct rectangle *p;
```
> Assume that we want `p` to point to a rectangle structure whose upper left corner is at $(10, 25)$, and whose lower right corner is at $(20, 15)$. Write a series of statements that allocate such a structure and initialize it as indicated.
```c
struct rectangle rect = { { 10, 25 }, { 20, 15 } };
p = &rect;
```
---
> **5.** Suppose that `f` and `p` are declared as follows:
```c
struct {
union {
char a, b;
int c;
} d;
int e[5];
} f, *p = &f;
```
> Which of the following statements are legal?
(a) `p->b = ' ';`
(b) `p->e[3] = 10;` - **Legal**
(c) `(*p).d.a = '*';` - **Legal**
(d) `p->d->c = 20;`
---
> **7.** The following loop is supposed to delete all nodes from a linked list and release the memory that they occupy. Unfortunately, the loop is incorrect. Explain what's wrong with it and show how to fix the bug.
```c
for (p = first; p != NULL; p = p->next)
free(p);
```
The above loop won't function because it deallocates the entry, then attempts to access the pointer to the next item, *after* it's already been freed.
A functional example might look like this:
```c
struct entry *p = first;
while (p != NULL) {
void *current = p;
p = p->next;
free(p);
}
```
---
> **9.** True or false: If `x` is a structure and `a` is a member of that structure, then `(&x)->a` is the same as `x.a`. Justify your answer.
**True**: The arrow operator is used to access a member of a struct through a pointer. `(&x)` creates a pointer to the `x` struct, therefore the arrow operator can be used to access fields on `x`.
---
> **13.** The following function is supposed to insert a new node into its proper place in an ordered list, returning a pointer to the first node in the modified list. Unfortunately, the function doesn't work correctly in all cases. Explain what's wrong with it and show how to fix it. Assume that the `node` structure is the one defined in Section 17.5.
```c
struct node *insert_into_ordered_list(struct node *list, struct node *new_node) {
struct node *cur = list, *prev = NULL;
while (cur->value <= new_node->value) {
prev = cur;
cur = cur->next;
}
prev->next = new_node;
new_node->next = cur;
return list;
}
```
In the above code, if the new item needs to be inserted at the *end* of the list, it breaks, because `cur` is set to `NULL`, then it attempts to access `cur->value`.
```c
struct node *insert_into_ordered_list(struct node *list, struct node *new_node) {
struct node *cur = list, *prev = NULL;
while (cur->value <= new_node->value) {
prev = cur;
cur = cur->next;
if (cur->next == NULL) {
break;
}
}
prev->next = new_node;
new_node->next = cur;
return list;
}
```

View File

@ -0,0 +1,47 @@
# \#2
Directives:
```c
#include <stdio.h>
```
Statements:
```c
printf("Parkinson's Law: \nWork expands so as to ");
printf("fill the time\n");
printf("available for its completion.\n");
return 0;
```
Output:
```
Parkinson's Law:
Work expands so as to fill the time
available for its completion.
```
# \#5
(A): `100_bottles` is not a legal C identifier because C identifiers cannot start with a number.
# \#6
Double underscores are typically used to denote statements reserved by the compiler, and in C++, double underscores are used in name mangling and so they cannot be used entirely. More subjectively, it can be hard to tell how many underscores are present.
# \#7
(A): `for`
(E): `while`
# \#8
14.
Work:
1. `answer`
2. `=`
3. `(`
4. `3`
5. `*`
6. `q`
7. `-`
8. `p`
9. `*`
10. `p`
11. `)
12. `/`
13. `3`
14. `;`

View File

@ -0,0 +1,37 @@
# 1.
a. `86,1040`
b. `3.02530e+01`
c. `83.1620`
d. `1e-06 `
# 2.
```c
float x = 0.12345;
// a
printf("%-8.1e", x);
// b
printf("%10.6e", x);
// c
printf("%8.3f", x);
// d
printf("%-6.0f", x);
```
# 3.
a. Equivalent
b. Equivalent
c. Equivalent
d. Equivalent
# 4.
`i`: `10`
`x`: `0.3f`
`j`: `5`
# 5.
`x`: `12.3f`
`i`: `45`
`f`: `0.6f`

View File

@ -0,0 +1,26 @@
# 1.
a. `1 2`
b. `0`
c. `1`
d. `0`
# 3.
a. `1`
b. `-1`, `-2`
c. `-1`, `-1`
d. `1`, `2`
# 9.
a. `63 8`
b. `1 2 3`
c. `0 1 3`
d. `0 0 0`
# 11.
a. `0 2`
b. `4 11 6`
c. `0 8 7`
d. `15 4 5 4`
# 15.
a. `i = 2, j = 2`
b. `i = 1`, `j = 2`
c. `i = 1`, `j = 2`
d. `i = 1`, `j = 3`

View File

@ -0,0 +1,103 @@
> 2. The following program fragments illustrate the logical operators. Show the output produced by each, assuming that `i`, `j`, and `k` are `int` variables.
a. `i = 10; j = 5;`
```c
printf("%d", !i < j);
// Expected output: `1`, because `!i` evaluates to 0, and 0 is less than 5, so that expression evaluates to true, or 1.
```
b. `i = 2; j = 1;`
```c
printf("%d", !!i + !j);
// Expected output: `1`, because !!2 evaluates to 1, and !j evaluates to 0
```
c. `i = 5; j = 0; k = -5;`
```c
printf("%d", i && j || k);
// Expected output: `1`, because i && j should evaluate to 0, but `0 || 1` should evalulate to true.
```
d. `i = 1; j = 2; k = 3;`
```c
printf("%d", i < j || k);
// Expected output: `1`
```
> 4. Write a single expression whose value is either `-1`, `0`, or `1` depending on whether `i` is less than, equal to, or greater than `j`, respectively.
```c
/*
If i < j, the output should be -1.
If i == j, the output should be zero
If i > j, the output should be 1.
*/
(i > j) - (i < j)
```
> 6. Is the following `if` statement legal?
```c
if (n == 1-10)
printf("n is between 1 and 10\n");
```
Yes the statement is *legal*, but it does not produce the intended effect. It would not produce an output when `n = 5`, because `1-10` evaluates to `-9`, and `-9 != 5`.
> 10. What output does the following program fragment produce? (Assume that `i` is an integer variable.)
```c
int i = 1;
switch (i % 3) {
case 0: printf("zero");
case 1: printf("one");
case 2: printf("two");
}
```
The program would print `onetwo` because each case is missing a `break` statement.
> 11. The following table shows the telephone area codes in the state of Georgia along with the largest city in each area:
| Area code | Major city |
| --------- | ---------- |
| 229 | Albany |
| 404 | Atlanta |
| 470 | Atlanta |
| 478 | Macon |
| 678 | Atlanta |
| 706 | Columbus |
| 762 | Columbus |
| 770 | Atlanta |
| 912 | Savannah |
> Write a switch statement whose controlling expression is the variable `area_code`. If the value of `area_code` is not in the table, the `switch` statement will print the corresponding city name. Otherwise, the `switch` statement will display the message `"Area code not recognized."` Use the techniques discussed in section 5.3 to make the `switch` as simple as possible.
```c
int area_code;
switch (area_code) {
case 404:
case 470:
case 678:
case 770:
printf("Atlanta");
break;
case 706:
case 762:
printf("Columbus");
break;
case 229:
printf("Albany");
break;
case 478:
printf("Macon");
break;
case 912:
printf("Savannah");
break;
default:
printf("Area code not recognized.");
break;
}
```

View File

@ -0,0 +1,58 @@
> 1. What output does the following program fragment produce?
```c
i = 1;
while (i <= 128) {
printf("%d ", i);
i *= 2;
}
```
Output:
```
1 2 4 8 16 32 64 128
```
> 2. What output does the following program fragment produce?
```c
i = 9384
do {
printf("%d ", i);
i /= 10;
} while (i <= 128);
```
Output:
```
9384 938 93 9
```
> 3. What output does the following `for` statement produce?
```c
for (i = 5, j = i - 1; i > 0, j > 0; --i, j = i - 1)
printf("%d ", i);
```
Output:
```
5 4 3 2
```
> 4. Which one of the following statements is not equivalent to the other two (assuming that the loop bodies are the same?)
```c
for (i = 0; i < 10; i++) // (a)
for (i = 0; i < 10; ++i) // (b)
for (i = 0; i ++ < 10; ) // (c)
```
Answer:
C is not the same as A and B, because the increment takes place before the loop body is executed.
> 5. Which one of the following statements is not equivalent to the other two (assuming that the loop bodies are the same)?
```c
while (i < 10) {...} // (a)
for (; i < 10;) {...} // (b)
do {...} while (i < 10); // (c)
```
Answer:
C is not the same as A and B, because the block is executed before the condition is checked.

View File

@ -0,0 +1,48 @@
> 3. Which of the following aren not legal types in C?
a. `short unsigned int`
b. `short float`
c. `long double`
d. `unsigned long`
Answer:
b. `short float`
> 4. If `c` is a variable of type `char`, which of the following statements is illegal?
```c
char c;
// A:
i += c; // i has type int
// B:
c = 2 * c - 1;
// C:
putchar(c);
// D:
printf(c);
```
Answer:
D is illegal because `printf` operates on strings, not `char`s.
> 6. For each of the following items of data, specify which one of the types `char`, `short`, `int`, or `long`is the smallest one guaranteed to be large enough to store the item.
Answer:
A. Days in a month: `char`
B. Days in a year: `short`
C. Minutes in a day: `short`
D. Seconds in a day: `long`
> 10. Suppose that `i` is a variable of type `int`, `j` is a variable of type `float`, and `k` is a variable of type `unsigned int`. What is the type of the expression `i + (int) j * k`?
Answer:
`unsigned int`
> 15. Use `typedef` to create types named `Int8`, `Int16`, and `Int32`. Define the types so that they represent 8 bit, 16 bit, and 32 bit integers on your machine.
Answer:
```C
typedef char Int8;
typedef short Int16;
typedef long Int32;
```

View File

@ -0,0 +1,69 @@
> 1. We discussed using the expression `sizeof(a) / sizeof(a[0]` to calculate the number of elements in an array. The expression `sizeof(a) / sizeof(t)` where `t` is the type of `a`'s elements would also work, but it's considered an inferior technique. Why?
Answer:
Using the type of the array's first element means that if you change the type of an array, it won't break the code that calculates the number of elements.
> 3. Write a declaration of an array named weekend containing seven `bool` values. Include an initialize that makes the first and last values `true`; all other values should be `false`.
Answer:
```c
bool weekend[] = {true, [1 ... 5] = false, true};
```
> 5. Calculators, watches, and other electronic devices often rely on 7 segment displays for numerical output. To form a digit, such devices turn on some of the seven segments while leaving others off.
>
> Here's what the array might look like, with each row representing one digit:
```c
const int segments[10][7] = {{1, 1, 1, 1, 1, 1, 0}, ...};
```
> I've given you the first row of the initializer, fill in the rest.
Answer:
```c
const int segments[10][7] = {
{1, 1, 1, 1, 1, 1, 0}, // 0
{0, 1, 1, 0, 0, 0, 0}, // 1
{1, 1, 0, 1, 1, 0, 1}, // 2
{1, 1, 1, 1, 0, 0, 1}, // 3
{0, 1, 1, 0, 0, 1, 0}, // 4
{1, 0, 1, 1, 0, 1, 1}, // 5
{1, 0, 1, 1, 1, 1, 1}, // 6
{1, 1, 1, 0, 0, 0, 0}, // 7
{1, 1, 1, 1, 1, 1, 1}, // 8
{1, 1, 1, 1, 0, 1, 1} // 9
};
```
>10. Write a declaration for an 8x8 `char` array named `chess_board`. Include an initializer that puts the following data into the array, one character per array element:
\[omitted]
```c
char chess_board[8][8] = {
{'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'},
{'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'},
{' ', '.', ' ', '.', ' ', '.', ' ', '.'},
{'.', ' ', '.', ' ', '.', ' ', '.', ' '},
{' ', '.', ' ', '.', ' ', '.', ' ', '.'},
{'.', ' ', '.', ' ', '.', ' ', '.', ' '},
{' ', '.', ' ', '.', ' ', '.', ' ', '.'},
{'.', ' ', '.', ' ', '.', ' ', '.', ' '},
{'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'},
{'R', 'N', 'B', 'K', 'Q', 'B', 'N', 'R'},
};
```
> 11. Write a program fragment that declares an 8x8 `char` array named `checker_board` and then uses a loop to store the following data into the array (one character per array element).
```c
char checker_board[8][8];
for (int row = 0; row < 8; row++) {
for (int column = 0; column < 8; column++) {
if ((column + row) % 2 == 0) {
checker_board[row][column] = 'B';
} else {
checker_board[row][column] = 'R';
}
}
}
```

View File

@ -0,0 +1,78 @@
> 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
#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`.

View File

@ -0,0 +1,322 @@
# Banana Cake
## Instructions
1. Assume an action set of {add \<ingredient>, stir, bake, cool}. Draw a flowchart, using the paradigm discussed in class, to show the process of baking a banana cake. Use Google to find a typical list of ingredients.
2. Represent the flowchart from problem 1 as pseudocode.
## Flowchart
```d2
vars: {
d2-config: {
dark-theme-id: 200
}
}
grid-columns: 3
begin: {
shape: oval
# near: top-left
}
begin -> add 3c flour\
-> add 1 1/2 tsp baking soda\
-> add 1/2 tsp cinnamon\
-> add 1/2 tsp salt\
-> stir\
-> add 3 mashed bananas\
-> add 1 tsp lemon juice\
-> stir again\
-> add 3 eggs\
-> add 2tsp vanilla extract\
-> stir a final time\
-> bake @ 350f for 50 min\
-> let cool for 1 hour\
-> end
end: {
shape: oval
# near: bottom-right
}
```
## Pseudocode
```c
/**************************************
* Function Title: BakeBananaCake
*
* Summary: Bake a banana cake
*
* Inputs: none
* Outputs: none
**************************************
* Pseudocode
*
* Begin
* Add 3c flour
* Add 1 1/2 tps baking soda
* Add 1/2 tsp cinnamon
* Add 1/2 tsp salt
* Stir
* Add 3 mashed bananas
* Add 1 tsp lemon juice
* Stir
* Add 3 eggs
* Add 2tsp vanilla extract
* Stir a final time
* Bake @ 350F for 50 min
* Cool for 1 hour
* End
**************************************/
```
# Walking
## Instructions
3. Assume an action set of {walk \<value> steps, turn to \<value> degrees}. Draw a flowchart showing a shady path and a sunny path to get from the west doors of the Engineering Building to the south-east doors of the TSC. Pick a meaningful “if” condition to select one of the two paths. Use real-world data in your design.
4. Represent the flowchart from problem 3 as pseudocode.
%%
Assuming a step distance of 2.5 feet.
Shady path:
1. Turn to 270 degrees
2. Walk 112 steps
3. Turn to 225 degrees
4. Walk 124 steps
5. Turn to 270 degrees
6. Walk 361 steps
7. Turn to 0 degrees
8. Walk 176 steps
9. Turn to 270 degrees
10. Walk 62 steps
Sunny path:
1. Turn to 270 degrees
2. Walk 73 steps
3. Turn to 0 degrees
4. Walk 94 steps
5. Turn to 275 degrees
6. Walk 467 steps
7. Turn to 180 degrees
8. Walk 86 steps
9. Turn to 270 degrees
10. Walk 80 steps
%%
## Flowchart
```d2
vars: {
d2-config: {
dark-theme-id: 200
}
}
classes: {
turn-0: {
label: turn to 0 degrees
}
turn-90: {
label: turn to 90 degrees
}
turn-180: {
label: turn to 180 degrees
}
turn-270: {
label: turn to 270 degrees
}
}
beginning: {shape: oval}
beginning -> if
if: {
shape: diamond
label: if (shady)\n<then else>\nendif
}
if -> shady: {
direction: up
label: if shady path
}
shady {
grid-columns: 2
1.class: turn-270
1 -> 2
2.label: walk 112 steps
2 -> 3
3.label: turn to 225 degrees
3 -> 4
4.label: walk 124 steps
4 -> 5
5.class: turn-270
5 -> 6
6.label: walk 361 steps
6 -> 7
7.class: turn-0
7 -> 8
8.label: walk 176 steps
8 -> 9
9.class: turn-270
9 -> 10
10.label: walk 62 steps
}
end: {shape: oval}
if -> end
if -> sunny: if sunny path
sunny {
grid-columns: 2
1.class: turn-270
1 -> 2
2.label: walk 73 steps
2 -> 3
3.class: turn-0
3 -> 4
4.label: walk 94 steps
4 -> 5
5.label: turn to 275 degrees
5 -> 6
6.label: walk 361 steps
6 -> 7
7.class: turn-0
7 -> 8
8.label: walk 176 steps
8 -> 9
9.label: turn to 270 degrees
9 -> 10
10.label: walk 80 steps
}
```
## Pseudocode
```c
/**************************************
* Function Title: WalkToTscFromEngr
*
* Summary: Walk from the west entrance of the engineering building
* to the southeast entrace of the taggart student center, using either
* a shady or sunny path
*
* Inputs: shady (boolean)
* Outputs: none
**************************************
* Pseudocode
*
* Begin
* If (shady) then
* Turn to 270 degrees
* Walk 112 steps
* Turn to 225 degrees
* Walk 124 steps
* Turn to 270 degrees
* Walk 361 steps
* Turn to 0 degrees
* Walk 176 steps
* Turn to 270 degrees
* Walk 62 steps
* Else
* Turn to 270 degrees
* Walk 73 steps
* Turn to 0 degrees
* Walk 94 steps
* Turn to 275 degrees
* Walk 467 steps
* Turn to 180 degrees
* Walk 86 steps
* Turn to 270 degrees
* Walk 80 steps
* EndIf
* End
**************************************/
```
# 4 Way Intersection
## Instructions
5. Develop a flowchart that describes the behavior of a set of traffic lights that control a 4-way intersection. Assume the light can either be red or green.  Define an appropriate action set that accounts for the time the light has been in the current state.
6. Represent the flowchart from problem 5 as pseudocode.
## Action Set
| Action name | Description |
| -- | -- |
| Set \[north, east, south, west] light to \[red, green] | Set the specified light to either red or green |
| Toggle lights | Change the color of all 4 lights to the color they were not |
| Wait \[number of seconds] seconds | Pause for \[number of seconds] seconds before continuing to the next instruction |
## Flowchart
```d2
vars: {
d2-config: {
dark-theme-id: 200
}
}
classes: {
toggle-lights: {
label: Toggle lights
}
}
beginning: {
shape: oval
label: beginning
}
beginning -> initialize lights
initialize lights {
grid-columns: 1
1.label: set the north light to red
1 -> 2
2.label: set the south light to red
2 -> 3
3.label: set the east light to green
3 -> 4
4.label: set the west light to green
}
initialize lights -> loop
loop {
near: center-right
label: loop indefinitely
begin-loop: {
shape: step
label: begin iteration
}
begin-loop -> 1
1.label: wait 30 seconds
1 -> 2
2.label: toggle lights
end-loop: {
shape: step
label: end iteration
}
2 -> end-loop
end-loop -> begin-loop
}
loop -> end: the heat death of the universe
end: {
near: bottom-right
shape: oval
label: end
}
```
## Pseudocode
```c
/**************************************
* Function Title: RunStopLights
*
* Summary: Operate stoplights for a 4 way intersection
*
* Inputs: none
* Outputs: none
**************************************
* Pseudocode
*
* Begin
* Set the north light to red
* Set the south light to red
* Set the east light to green
* Set the west light to green
* Loop indefinitely
* Wait 30 seconds
* Toggle lights
* EndLoop
* End
**************************************/
```