lesson 10 Conditional statements If conditional statement
Conditional statements
![Kotlin-logo.png]()If conditional statement: Conditional statements are used when we want code to be executed when a condition is true
If form
If (condition) {
// block of code
}
For example:
fun main (args:Array <String>){
println("enter a number:")
var number:Int = readLine()!!.toInt()
if ((number >= 0) && (number <= 10)){
println("your number is smaller than 10")
}
}
In this example, we asked the user to enter a number then stored the number in a variable of Int type
The expression if ((number> = 0) && (number <= 10)) means that if the input number is greater than or equal to 0 and smaller or equal to 10,
println ("your number is less than 10")
That is, the statement will only be executed if both conditions are met:
condition: number> = 0
And condition: number <= 10
If either of them is not achieved, the phrase
println ("your number is less than 10")
It will not execute and will move to the commands and statements that follow the if conditional statement
But what if we had more than one condition or more probability?
Then we use the if-else statement if we have two conditions or two probability
We use if - else if - else if - ... - else if we have several conditions or situations
For example, we want to classify the level of the student according to his mark:
fun main (args:Array <String>){
print("enter your grade: ")
var grade:Double = readLine()!!.toDouble()
if ( grade >= 0 && grade < 50){
println("you faild")
}else if (grade >=50 && grade < 70){
println("you are level B and your grade is $grade")
}else{
print("you are level A and your grade is $grade")
}
}
In this example the user will enter the student's grade and store it in the grade variable its Type Double
If the grade is less than 50, the result will be ( you fail )
This is what we tested from the term
If (grade> = 0 && grade <50)
If the grade entered is greater or equal to 50 and is completely smaller than 70, the result will appear on the screen (You are level B and your grade is "the entered grade")
This is what we have seen from the condition
else if (grade> = 50 && grade <70)
If the input grade is greater than or equal 70, it will appear on the screen (You are level A and your grade is "the entered grade")
And this is what we have experienced from the condition else
Q: Try improving the previous program by making more classifications