Conditional Statements: If, If-Else
if() is a keyword in C++ which allows for conditional execution of code.
The syntax for the if statement is:
if (ConditionExpression){
ThenStatementBlock;
}
else {
ElseStatementBlock;
}
· ConditionExpression contains the test expression. If the test expression evaluates to true (ie. non-zero), ThenStatementBlock is executed, otherwise the ElseStatementBlock is executed.
· If there is more than one statement to be executed within the ThenStatementBlock or ElseStatementBlock branch, the blocks must be enclosed with {}'s.
· It is not necessary to have an else statement within each if() conditional.
· Multiple expressions can be evaluated by using conjunctions (e.g. &&, ||).
· Indent your programs to increase readability.
· Do not confuse the uses of assignment (=) and equality (==) operators, especially within the test condition. They can have adverse effects on your program.
· In some cases, a switch() statements can be used to simplify several nested if() statements.
Examples
MULTIPLE ELSE-IF COMPARISONS:
#include
int main()
{
// Obtain package information
double Weight, Length, Width, Height ;
cout << "Enter weight of package in kilograms: ";
cin >> Weight;
cout << "Enter length of package in meters: ";
cin >> Length;
cout << "Enter width of package in meters: ";
cin >> Width;
cout << "Enter height of package in meters: ";
cin >> Height;
double CubicMeters = (Length * Width * Height);
// else-if ladder to check package requirements and display appropriate message
if ((Weight > 27) && (CubicMeters > 0.1))
cout << "Rejected: Too heavy and too large" << endl;
else if(Weight > 27)
cout << "Rejected: Too heavy" << endl;
else if (CubicMeters > 0.1)
cout << "Rejected: Too large" << endl;
else
cout << "Package accepted" << endl;
return(0);