Control Flow: [If-Else]
Hello Friends,
In this post, we will start with conditional statements.
In conditional statements, the execution of a statement depends upon the condition.
Swift provides if–else and switch as conditional statements.
For now, we will concern ourselves to if-else statements.
The following block of code specifies how the if-else statements are written in swift.
if ( condition ){ //execute block1 } else { //execute this block2 }
If the condition is true, block1 executes else block2 executes.
This will be more clear once we look into some examples.
If Statement
Example: We have a variable marksOfStudents. If the marks are less than 30, we will print fail. The code will be like this
var marksOfStudents = 25 if ( marksOfStudents <= 30 ){ print("Student Fails") }
Here we check in the condition whether marks are less than and equal to 30. Since the condition is true “Student Fails” gets printed.
Suppose the condition is false. marksOfStudent = 45 (> 30). Let’s see what happens
var marksOfStudents = 45 if ( marksOfStudents <= 30 ){ print("Student Fails") }
There is no output. Because we have not coded the false condition.
Else Statement
To code the false condition, else is used. The code will now become:
var marksOfStudents = 45 if ( marksOfStudents <= 30 ){ print("Student Fails") } else { print("Student Passes") }
We can see from the output, “Student Passes” is printed as condition is false.
Else-If Statement
Suppose we want to print division and fail base upon the marks. If marks are greater than 75, we want to award “First Division”. If marks are greater than 30 but less than 75, we want to award “Second Division”, If marks are less than 30, we want to declare “Student fails”
We can see there are multiple conditions here, which cannot be handled using only if-else. So here, we will use if-else-if. The else-if statement is used to handle additional conditions.
Let’s see how the code for this one would look like:
var marksOfStudents = 45 if ( marksOfStudents >= 75 ){ print("First Division") } else if (marksOfStudents >30 && marksOfStudents < 75) { print("Second Division") } else { print("Student fails") }
As we can see from the code, first we check the condition whether marks are greater than or equal to 75 using if. Next we check the middle condition whether marks are between 30 and 75 using the else if. Finally we use else to handle the situation when both the conditions become false.
The output is second division. Here the else-if condition becomes true as 45 is less than 75 and greater than 30.
The code for this post is available here.