Conditional 'If'
'If' statements are used to examine the boolean values (true/false) and control the flow of program according to the boolean value.
A basic if statement can be expressed as following :
if ( condition )
{
execute this statement if the condition is true
}
The statement can be further expressed as :
if ( condition )
{
execute this statement if the condition is true
} else {
execute this statement if the condition is false
}
Negation of condition uses '!' (exclamation mark)
If an exclamation mark is put before a condition, the boolean value of the statement is negated.
if ( !condition )
{
execute this statement if the condition is false
}
OR boolean operator
OR boolean operator (||) can be used to join two or more statements and the joint statement will only return true if one or more of the statement is true.
if ( condition1 || condition2 )
{
execute this statement if condition1 is true or condition2 is true or both are true
}
AND boolean operator
AND boolean operator (&&) can be used to join two or more statements and the joint statement will only return true if all of the statements is true.
if ( condition1 && condition2 )
{
execute this statement if both condition1 and condition2 are true
}
Practice
using namespace std ;
string today = " " ;
string weather = " " ;
if ( today == "saturday" || today == "sunday" )
{
cout<<" Turn alarm off "<< endl ;
}
else
{
cout<<" Set alarm at 7am "<< endl ;
}
if ( today == "monday" && weather == "rainy" )
{
cout<<" I hate monday blues "<< endl ;
}
else
{
cout<<" Just a normal day "<< endl ;
}
string today = " " ;
string weather = " " ;
if ( today == "saturday" || today == "sunday" )
{
cout<<" Turn alarm off "<< endl ;
}
else
{
cout<<" Set alarm at 7am "<< endl ;
}
if ( today == "monday" && weather == "rainy" )
{
cout<<" I hate monday blues "<< endl ;
}
else
{
cout<<" Just a normal day "<< endl ;
}
Output
Set alarm at 7am
Just a normal day
Just a normal day