3️⃣

4.3 Applications of Structures

 

Else-If Statements

What if you have more than two scenarios that could apply? Well, you could also use an else if statement to account for those other scenarios. Below is a continuation of the code from the previous sections, this time including an else if statement:
 
int num1 = 5; int num2 = 3; if (num1 > num2) { printf(“num1 is greater than num2”); } else if (num1 < num2) { printf(“num1 is less than num2”); } else { printf(“num1 is equal to num2”); }
 
In the above example, notice that the else if statement comes after the if statement, but before the else statement. Like the if statement, the else if statement contains a condition to be checked in a set of parentheses, and then contains some code that should be executed within a set of curly braces.
 
Specific to the example used in these sections, notice that the first if statement checks if num1 is greater than num2, and then the else if statement checks if num1 is less than num2. If a number is not greater than another number AND it is not less than that number, it must be equal to that number.
 
That is why it is not necessary for us to use an else if statement to check if the numbers are equal. Technically, you could have used an else if statement if you wanted to, but logically, it makes more sense to use an else statement since there are no other possible scenarios in this case.

Previous Section

Next Chapter

 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.