File tree Expand file tree Collapse file tree
exercises/25_conditional_expressions Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Conditional expressions
2+
3+ For more information please refer to Chapter 2.11 of "The C Programming Language".
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments