If / else Statement-
//Deciding on different path of execution . Decision making is done with if and else statements --
//Executed if marks greater than or equal to 60
Chained conditions -
//In case where there are more than two possible paths of execution . you can use the if/else if/else block
//Deciding on different path of execution . Decision making is done with if and else statements --
//Executed if marks greater than or equal to 60
if marks >= 60
{
print("you score first division")
}
else
{
print("you not score first division")
}
//In case where there are more than two possible paths of execution . you can use the if/else if/else block
var marks = 60
if marks >= 60
{
print("you score first division")
}
else if marks >= 50
{
print("you score second division")
}
else if marks >= 40
{
print("you score third division")
}
else
{
print("you failed")
}
Logical Operators - && and ||
Use && operator to make complex decisions involving two (or more) conditions . The result is "true" only if both conditions evaluate true.
The || operator works in the same way . The result is true if either one of the conditions evaluates to true
//Passed both test
//Pass at least one test
Nested if/else statements -
Use && operator to make complex decisions involving two (or more) conditions . The result is "true" only if both conditions evaluate true.
//output is true
print(true && true)
//output is false
print(false && true)
//output is false
print(true && false)
//output is false
print(false && false)
The || operator works in the same way . The result is true if either one of the conditions evaluates to true
//output is true
print(true || true)
//output is true
print(false || true)
//output is true
print(true || false)
//output is false
print(false || false)
Example of using && and ||
func getResult (english: Int, science: Int){
if(english >= 60 && science >= 60)
{
print("Passed both test")
}
else if(english >= 60 || science >= 60)
{
print("pass at least one test")
}
else
{
print("fail")
}
}
//Passed both test
getResult(50, 60)
getResult(60, 70)
//Fail
getResult(8, 8)
var gender = "M"
var age = 18
var discount: Int;
if gender == "M"{
//execute if gender is male
if age > 18{
discount = 10 //discount (10) if male is above 18
}else{
discount = 5 //discount (5) if male is below 18
}
}else{
//execute if gender is not male
if age > 18{
discount = 20
}else{
discount = 15
}
}
No comments:
Post a Comment