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.
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:
if
;else{...}
is optional;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");
}
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");
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");
==
. Do not confuse it with the assignment operator =
.Write a program that asks the user to enter his or her grade point average.
Enter your grade point average: 10.0
Congratulations! You graduated.
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
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
What does the following code display?
if (4<2)
printf ("Crac");
else
printf ("Boum");
else
.
Try again...
When can you omit the curly braces?
What does the following code display?
if (0)
printf ("Crac");
printf ("Boum");
if
. This kind of presentation should be avoided.
Try again...
What does the following code display?
if (0)
printf ("Crac"); printf ("Boum");
if
. This kind of presentation should be avoided.
Try again...
What does the following code display?
if (0);
printf ("Crac");
printf ("Boum");
if
(after the test)!
Try again...
When can the test parentheses be omitted?