Lesson 5.1. Conditional branching (if...else)

The `if...else` instruction executes a block of instructions depending on the result of a test:

If the weather is nice, I'll go for a run, otherwise I'll work on my C class.

Syntax

Here is the syntax of the `if...else` statement:

``````if (test) {
...
// Instruction block 1
}
else {
...
// Instruction block 2
}``````

The first block of instructions will only be executed if the test is true.

It should be noted that:

• do not put a semicolon at the end of the `if`;
• parentheses in the test are mandatory;
• the `else{...}` is optional;
• braces can be omitted if the block contains only one statement.

Example 1

This example displays two different messages depending on whether A is larger than B or not:

``````if (A>B) {
printf ("A is greater than B\n");
}
else {
printf ("A is smaller than or equal to B\n");
}``````

Example 2

In the previous example, each instruction block contains only one statement. The code can be simplified by omitting the braces:

``````if (A>B)
printf ("A is greater than B\n");
else
printf ("A is smaller than or equal to B\n");``````

Example 3

This example illustrates the optional nature of the `else {}` :

``````// Compare A and B
if (A>B) printf ("A is greater than B\n");
if (A<B) printf ("est plus petit que\n");
if (A==B) printf ("A is equal to B\n");``````
The comparison operator is the double equal `==`. Do not confuse it with the assignment operator `=`.

Exercises

Exercise 1

Write a program that asks the user to enter his or her grade point average.

• If the average is greater than or equal to 10, the program displays "Congratulations! You graduated.";
• otherwise, it displays "Maybe next time!".
``````Enter your grade point average: 10.0

Exercise 2

Write a program that asks the user to enter a number between 0 and 9 included. The program then displays the number in words. We will assume that the user enters a valid number (there is no need to check the input):

``````Enter a number [0;9]: 4
4 is written four``````

Exercise 3

Write a program that asks the user to enter two integers (`x1` and `x2`). If `x1` is not smaller than `x2`, the contents of the variables are swapped. At the time of display, `x1` must always be smaller than `x2` :

``````Enter the first integer: 5
Enter the second integer: 3
x1=3    x2=5``````
``````Enter the first integer: 3
Enter the second integer: 5
x1=3    x2=5``````

Quiz

What does the following code display?

``````if (4<2)
printf ("Crac");
else
printf ("Boum");``````

When can you omit the curly braces?

What does the following code display?

``````if (0)
printf ("Crac");
printf ("Boum");``````

What does the following code display?

``````if (0)
printf ("Crac"); printf ("Boum");``````

What does the following code display?

``````if (0);
printf ("Crac");
printf ("Boum");``````

When can the test parentheses be omitted?