notes/education/software development/ECE1400/Chapter.md
2024-09-18 11:37:12 -06:00

48 lines
1.3 KiB
Markdown

> 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 produce an output when `n` is zero because `0 >= 1` would evaluate to `0`, and `0 <= 10` is false.