If-else
statements are used in cases where a certain requirement/condition needs to be fulfilled in order for an action to be completed.
The if
statement allows a block of code, inside of it, to be executed if the condition provided is met. If the condition is not met, the block of code inside of the else
statement is executed.
Let’s first have a look at the syntax of the basic If-else
statement in C
if (condition) {//code//These statements will only execute if the condition is met}else {//code//These statements will execute if the condition is not met}
Let’s have a look at an example of how to use a basic If-else
statement in C.
Here’s a scenario:
An instructor needs to mark the quizzes of his class as either Pass or Fail. A student only passes if he/she obtains at least 60 marks (out of a possible 100).
Let’s break down the scenario.
What is the condition?
So if
the condition is met, what happens? The student passes.
Else
what happens? The student fails. Let’s put this in code and do this for three different marks
int main(){int marks1 = 45;int marks2 = 60;int marks3 = 80;if(marks1 >= 60) {printf("Student 1: PASS! \n");}else {printf("Student 1: FAIL!\n");}if(marks2 >= 60) {printf("Student 2: PASS! \n");}else {printf("Student 2: FAIL! \n");}if(marks3 >= 60) {printf("Student 3: PASS! \n");}else {printf("Student 3: FAIL! \n");}return 0;}
Only Student 1’s marks were below 60 while the other 2 students have more than, or equal to, 60 (remember that a student with exactly 60 marks also passes!).
Hence, the code in the else
block was executed for student 1 since, his/her condition wasn’t fulfilled.
For the other two, the code in the if
block was executed since they met the condition.
Free Resources