Conditional Statement
This is the first time where our code starts branching, that is, doing different things depending on some value.
The if
statement looks like this:
if (condition)
...
else
...
The condition
is any expression, it will be evaluated to either 0, which means "false", or anything else, which means "true". The first ...
is the statement which will be executed if the condition is true, and the second ...
will be executed if the condition is false:
if (a > b)
printf("a is greater than b\n");
else
printf("a is not greater than b\n");
The else
branch is optional, so this is perfectly valid too:
if (a > b)
printf("a is greater than b\n");
Semicolons in C
You might have noticed that each printf
line above ends with a semicolon; this is because in C, the majority of statements end with semicolons. The semicolon discussion is, surprisingly, not that trivial and requires talking about the grammar of C, which we might do later, but for now, please remember that you must end your statements with semicolons, unless explicitly told not to.
Refresher: functions
We mentioned functions a few pages ago. As a reminder, a function is defined like this:
int calculate_amount(int price, int count) {
return price * count;
}
and then it can be called like x = calculate_amount(5, 3)
(which will assign the value 15 to variable x
). return
is a statement that says "here's the result of the function", and, as you notice, it also ends with a semicolon.
Let's combine what we remember about the functions, and write a function that would return the greater of two numbers. I'll help you with the code to call this function for now, and make sure to edit the code to have the tests pass! You need to write an if
statement inside function max
to return
the greater of a
and b
.
#include <stdio.h>
int max(int a, int b) {
/* edit this function */
return 0;
}
int main() {
printf("greater of 5 and 7 is %d\n", max(5, 7));
printf("greater of 7 and 5 is %d\n", max(7, 5));
printf("greater of 3 and 3 is %d\n", max(3, 3));
return 0;
}