notes/education/software development/ECE1400/Chapter 13 Exercises.md

70 lines
2.3 KiB
Markdown
Raw Permalink Normal View History

2024-11-03 21:20:04 +00:00
> **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.
2024-11-03 20:03:05 +00:00
2024-11-03 21:05:04 +00:00
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.
2024-11-03 21:10:04 +00:00
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`.
2024-11-03 21:15:04 +00:00
j. `puts("\n");` - `puts` will write a newline after writing a string, so this will write two newlines.
2024-11-03 21:25:04 +00:00
---
2024-11-03 21:15:04 +00:00
2024-11-03 21:20:04 +00:00
> **2.** Suppose that `p` has been declared as follows:
2024-11-03 21:15:04 +00:00
```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`
2024-11-03 21:20:04 +00:00
putchar(*p);
// C - Legal, output: `abc`
puts(p)
// D - Illegal, `puts` accepts a pointer to a null terminated string, not a `char`.
```
2024-11-03 21:25:04 +00:00
---
2024-11-03 21:15:04 +00:00
2024-11-03 21:20:04 +00:00
> **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.)
2024-11-03 21:25:04 +00:00
- `i`: `12`
- `s`: `"abc34"`
- `j`: `56`
---
2024-11-03 21:30:04 +00:00
> **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
2024-11-03 21:35:04 +00:00
// Assuming `str` is an empty string with enough space to store everything:
2024-11-03 21:30:04 +00:00
strcpy(str, "tire-bouchon");
2024-11-03 21:35:04 +00:00
// "tire-bouchon"
strcpy(&str[4], "d-or-wi");
// "tired-or-wir"
strcat(str, "red?");
// "tired-or-wired?"
```
Expected output:
```c
"tired-or-wired?"
2024-11-03 21:30:04 +00:00
```