Hi, Welcome to the 3rd article in this series. In this article, I will talk about Selection statements in C++. But before that let's explore different types of statements.
What are statements?
Statements are instructions given to the computer to perform any kind of action. They form the smallest executable unit within a C++ program. Statements are terminated with a semicolon ( ; ).
It can be a simple statement such as this.👇
int profit = SellingPrice - CostPrice ;
or, it can be a sequence of simple statements enclosed by a pair of braces {}. For instance,
{
statement1;
statement2;
.
.
.
}
Statement Flow Control
In a program, statements may be executed sequentially, selectively or iteratively. Let us see what these mean.
- Sequence
The sequence construct means the statements are being executed sequentially i.e, one after the another. This represents the default flow of the statement. Every C++ program begins with the first statement of main()**.* When the last statement of main()* is executed, the program is done.
- Selection
The selection construct means the execution of statement(s) depending upon a condition-test. If the condition evaluates to true, a course of action (a set of statements) is followed otherwise another course of action (set of statements) is followed. This construct is also called the decision construct.
- Iteration
The iteration construct means the repetition of a set-of-statements depending upon a condition-test. Till the time a condition is true (or false depending upon the loop), a set-of-statements are repeated again and again. As soon as the condition becomes false(or true), the repetition stops. Such iteration construct is called a looping construct. The condition on which the execution or exit of the loop depends is called the exit condition or test-codition.
As you have seen selection and iteration constructs depend upon a conditional expression that determines what course-of-action is to be taken. A conditional expression evaluates to either true or false. In C++, any nonzero value is a true value including negative numbers. A 0 (zero) is treated as false.
In this article, we will look at selection statements and in the upcoming article we will learn about iterative statements.
Selection Statements
C++ provides two types of selection statements: if and switch
The if Statement of C++
An if statement tests a particular condition; if the condition evaluates to true, a course-of-action is followed i.e, a statement or set of statements is executed. Otherwise, the course of action is ignored. The general syntax of an if statement is as follows:
if (expression)
statement;
where a statement may consist of a single statement, a compound statement or nothing. The expression must be enclosed within parentheses. If the expression evaluates to true, the statement is executed, otherwise ignored.
Consider this example:
if (x)
{
cout<<"x is non-zero";
}
if (!x)
cout<<"!x is zero this time";
If the value of x is zero, The above code will display :
!x is zero this time
And for non-zero values of x, it will display :
x is non -zero
The expression can contain a variety of test-conditions, such as:
if(grade == 'A' || grade == 'a')
cout<<"Excellent";
if(a>b)
cout<<"A has more than B has";
if ((x >= 2) && (x<= 10))
{ //The if body contains a compound statement
cout<<"x is greater than 2 and less than 10";
x = x+20;
}
Now, what if there is another course of action to be followed if the expression evaluates to false? There is another form of if that allows for this kind of either-or condition by providing the else clause. The syntax of an if-else statement is:
if(expression)
statement 1;
else
statement 2;
If the expression evaluates to true, statement-1 is executed, otherwise, statement-2 is executed. Statement-1 and statement-2 can be a single statement, compound statement or null statement.
if (100 > x)
cout<<" 100 is greater than x";// if 100>x evaluate to true
else
cout<<" 100 is smaller than x"; //if 100>x evaluate to false
Nested ifs:
A nested if is an if that has another if in its if's body or in its else's body. It can have one of three forms:
CLICK HERE for an example program which illustrates the use of nested ifs.
The Dangling-Else Problem
The nested if-else statement introduces a source of potential ambiguity referred to as a dangling-else problem. This problem arises when in a nested if statement, the number of ifs is more than the number of else clauses. The question then arises, with which if does the additional else clause property matchup? For instance,
if(ch>= 'A')
if(ch <= 'Z')
++upcase;
else
++others;
The indentation in the above code fragment indicates that we want the else to be with the outer if. However, C++ matches an else with the preceding unmatched if. In this case, the actual evaluation happens something like this:
if(ch>= 'A')
if(ch<= 'Z') //---the else clause matches up with this if statement
++upcase;
else
++others;
That is, if the inner expression is false i.e, zero then the else clause gets executed.
What if you want to override the default dangling-else matching? i.e, consider:
if(exp1)
if(exp2)
statement1;
else
statement2;
you want the else to go with the other if. (By default, it will go with the inner if).
One method of overriding the default dangling-else matching is to place the last occurring unmatched if in a compound statement, as shown below:
if(exp1)
{
if(exp2)
statement1;
}
else //Now wlse matches up with the outer if.
statement2;
CLICK HERE to view the program illustrating the use of dangling-else matching.
The if-else-if Ladder:
It takes the following general form:
if(expression 1)
statement 1;
else if(expression 2)
statement 2;
else if(expression 3)
statement 3;
.
.
else
statement 4;
The expressions are evaluated from the top downward. As soon as an expression evaluates to true, the statement associated with it is executed and the rest of the ladder is bypassed. If none of the expressions is true, the final else gets executed. If the final else is missing, no action takes place if all other conditions are false.
CLICK HERE for a program which illustrates the if-else-if ladder.
The Switch Statement
C++ provides a multiple-branch selection statement known as switch. This selection statement successively tests the value of an expression against a list of integers or character constants. When a match is found, the statements associated with that constant are executed.
The syntax of switch is as follows:
switch (expression)
{
case constant1 : statement sequence 1;
break;
case constant2 : statement sequence 2;
break;
case constant3 : statement sequence 3;
break;
.
.
.
case constant n-1 :statement sequence m-1;
break;
default : statement sequence n;
The expression is evaluated and its values are matched against the values of the constants specified in the case statements. When a match is found, the statement sequence associated with that case is executed until the break statement or the end of the switch statement is reached. If the case statement does not include a break statement, then the control continues right on the next case statement(s) until either a break is encountered or the end of switch is reached. This situation is called a fall-through.
The default statement gets executed when no match is found. The default statement is optional and, if it is missing, no action takes place if all matches fail. The break statement is one of C++ jump statements. When a break statement is encountered in a switch statement program execution jumps to the line of code following the switch statement i.e, outside the body of switch statement.
CLICK HERE to view the program which illustrates the switch statement.
Now, you may be confused by seeing the switch statement. It does a similar job to if-else. So, let us see the key differences between the two.
The Switch Vs If-Else
Switch can only test for equality whereas if can evaluate a relational or logical expression i.e, multiple conditions.
The switch statement selects its branches by testing the value of same variable against a set of constants whereas, the if-else construction lets you use a series of expressions that may involve unrelated variables and complex expressions.
The if-else statement can handle floating-point tests also apart from handling integer and character tests whereas a switch cannot handle floating-point tests. The case label of switch must be an integer ( which includes char also)
The switch statement is a more efficient choice in terms of code used in a situation that supports the nature of switch operation (testing a value against a set of constants)
The Nested-Switch:
Like if statements, a switch statement can also be nested. There can be a switch as part of the statement sequence of another switch. For example:
switch(a)
{
case 1 : switch (b)
{
case 0 : cout<<"inside nested-switch case 0";
break;
case 1 : x= (a+b)/2;
break;
}
break;
case 2 :
.
.
.
}
Some Important Things About Switch Statement
A switch statement can only work for equality comparisons.
No two case labels in the same switch can have identical values. But, in the case of nested switch statements the case constants of the inner and outer switch can contain common values.
If character constants are used in the switch statement, they are automatically converted to their integers. (i.e, their equivalent ASCII codes)
Remember to always put the break statement after the last case statement in a switch.
Thats it folks. If you have followed along until the end, you must have a basic understanding of C++ selection statements. So, stop not! Pickup a few questions on these and start coding🧑💻.
Please feel free to start a discussion in the comments section, react to this article and stay tuned for more C++.🤠