Skip to content

Commit b37c043

Browse files
authored
Exercise: Conditional Expressions
1 parent 27dc8a6 commit b37c043

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Conditional expressions
2+
3+
For more information please refer to Chapter 2.11 of "The C Programming Language".
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
* Rewrite the `to_upper` function from the previous exercise without using an `if` statement.
3+
* Instead, use a conditional (ternary) expression.
4+
*
5+
* A conditional expression looks like this:
6+
* condition ? value_if_true : value_if_false
7+
*
8+
* For example:
9+
* z = (a > b) ? a : b;
10+
*
11+
* In this example, if `a` is greater than `b`, then `z` will be assigned the value of `a`.
12+
* Otherwise, `z` will be assigned the value of `b`.
13+
*
14+
* Conditional expressions can sometimes make the code easier to read.
15+
*/
16+
17+
#include <assert.h>
18+
#include <stdio.h>
19+
#include <string.h>
20+
21+
// ❌ I AM NOT DONE
22+
23+
char to_upper(char c) {
24+
// Rewrite
25+
if(c >= 'a' && c <= 'z') {
26+
return c - 32;
27+
}
28+
29+
return c;
30+
// Rewrite
31+
}
32+
33+
int main() {
34+
char s[] = "hello, world!";
35+
36+
for(int i = 0, len = strlen(s); i < len; i++) {
37+
s[i] = to_upper(s[i]);
38+
}
39+
40+
printf("%s\n", s);
41+
42+
assert(strcmp(s, "HELLO, WORLD!") == 0);
43+
return 0;
44+
}

0 commit comments

Comments
 (0)