Conditional Statements
Conditional statements allow the programmer to create choices.
A real world application is our internal body code performing choices. For example, if you're lacking oxygen your body might force itself to yawn. Something in your body is telling you that there is a lack of oxygen, so it performs the task of yawning in lieu of that information.
C provides us two ways to perform choices. The first is the if statement, alongside the else statement. The second is the switch statement.
if
An if statement checks if a condition is true. Once it determines the truth of the statement it executes the block provided in the curly brackets.
Example 1.1
int a = 5
if (a == 5) {
/* do something* /
}
The == represents equality in the program. It asks if two variables contain an equal value. So the code above is asking if a is equal to 5, then do something. If a was not equal to 5 then the code would not execute. Also, make sure you include the curly brackets and the indent to indicate the block as part of your if statement.
if - else
You can append an else block to execute a different block if the if condition is false.
Example 1.2
int a = 5
if (a == 2) {
/* do something* /
} else {
/* do something else* /
}
This code is asking if a is not equal to 2, then perform the action in the else block.
You can perform multiple else blocks by stacking multiple if statements.
Example 1.3
int a = 5
if (a == 2) {
/* do something */
} else if (a==5) {
/* do something else */
} else {
/* do something else again */
}
switch
A switch statement can be useful when you need to test the exact value of a variable. It tests for equality against a list of values, each called a case.
switch (a) {
case 0:
/* do something */
break;
case 1:
/* do something else */
break;
case 2:
/* do another something else */
break;
}
Again, it is very important to indent properly to make sure that the switch statement is applied to each switch case.
We also need a break keyword at the end of every case to stop the next case from executing before the prior ends.
default
Default can be put at the end of all the other cases. It is executed if no case constant-expression is equal to the initial value. If there is no default statement and no case matches, non of the statement in the switch will be executed (Microsoft). If you input more than one default clause you will get a syntax error, so don't do that!
Test Your Knowledge
int x = 10;
if (x == 5) {
printf("The magic number is 10")
What will be printed?
Answer
Nothing! It's false.
Thats a wrap on conditional statements. If you practiced alongside, then you will be a master coder!