Selection
statements
In
a program a decision causes a one time jump to a different part of a program.
Decisions in C++ are made in several ways, most importantly with if .. else …
statement which chooses between two alternatives. Another decision statement ,
switch creates branches for multiple alternatives sections of code, depending
on the value of a single variable.
The
if statement evaluates a condition, if the condition is true then a true-block
(a statement or set of statements) is executed, otherwise the true-block is
skipped.The general syntax of the if statement is:
if (expression)
true-block;
statement-x;
In
the above syntax, if is a keyword
that should contain expression or condition which is enclosed within
parentheses. If the expression is true (nonzero) then the true-block is
executed and followed by statement-x are also executed, otherwise, the control
passes to statement-x. The true-block may consists of a single statement, a
compound statement or empty statement. The control flow of if statement and the
corresponding flow chart is shown below.
#include<iostream>
using namespace std;
int main()
{
int qty, dis=0;
float rate, tot;
cout<<"\nEnter
the quantity ";
cin>>qty;
cout<<"\nEnter
the rate ";
cin>>rate;
if ( qty> 500)
dis=10;
tot = (qty * rate) -
( qty * rate * dis / 100);
cout<<"The
total expenses is "<< tot;
return 0;
}
First Run
Enter the quantity 550
Enter the rate 10
The total expenses is 4950
Second Run
Enter the quantity 450
Enter the rate 10
The total expenses is 4500
In
the first execution of the program, the test condition evaluates to true, since
qty>
Therefore,
the variable dis which is initialized to 0 at the time of declaration, now gets
a new value 10. The total expenses is calculated using a new dis value.
In
the second execution of the program, the test condition evaluates to false,
since qty> 500. Thus, the variable dis which is initialized to 0 at the time
of declaration, remains 0. Hence, the expression after the minus sign evaluates
to 0. So, the total expenses is calculated without discount.
#include
<iostream>
using namespace std;
int main()
{
int age;
cout<< "\n Enter your age:
";
cin>> age; if(age>=18)
cout<< "\n You are eligible for
voting ....";
cout<< "This statement is
always executed.";
return 0;
}
Enter your age: 23
You are eligible for voting….
This statement is always executed.
#include<iostream>
using namespace std;
int main()
{
int bonus,yr_of_ser;
cout<<"\nEnter your year of service ";
cin>>yr_of_ser;
if ( yr_of_ser> 3
)
{
bonus=2000;
cout<<"\n
Your bonus is " <<bonus;
}
cout<<"\nCongratulations...";
return 0;
}
Enter your year of service 5
Your bonus is 2000
Congratulations...
In
the above examples of if, you have seen so for allow you to execute a set of
statement is a condition evaluates to true. What if there is another course of
action to be followed if the condition evaluates to false. There is another
form of if that allows for this kind of either or condition by providing an
else clause. The syntax of the if-else statement is given below:
if ( expression)
{
True-block;
}
else
{
False-block;
}
Statement-x
In
if-else statement, first the expression or condition is evaluated either true
of false. If the result is true, then the statements inside true-block is
executed and false-block is skipped. If the result is false, then the statement
inside the false-block is executed i.e., the true-block is skipped.
#include <iostream>
using namespace std;
int main()
{
int num, rem;
cout<< "\n
Enter a number: ";
cin>>num;
rem = num % 2;
if (rem==0)
cout<<
"\n The given number" <<num<< " is Even";
else
cout<<
"\n The given number "<<num<< " is Odd";
return 0;
}
Enter number: 10
The given number 10 is Even
In the above program, the remainder of the given number is stored in rem. If the value of rem is zero, the given number is inferred as an even number otherwise, it is inferred as on odd number.
An
if statement contains another if statement is called nested if. The nested can
have one of the following three forms.
1.
If nested inside if part
2.
If nested inside else part
3.
If nested inside both if part and else part
The
syntax of the nested if:
If nested inside if
part
if (expression-1)
{
if
(expression)
{
True_Part_Statements;
}
else
{
False_Part_Statements;
}
}
else
body
of else part;
If nested inside else
part
if (expression-1)
{
body
of else part;
}
else
{
if
(expression)
{
True_Part_Statements;
}
else
{
False_Part_Statements;
}
}
If nested inside both
if part and else part
if (expression)
{
if
(expression)
{
True_Part_Statements;
}
else
{
False_Part_Statements;
}
}
else
{
if
(expression)
{
True_Part_Statements;
}
else
{
False_Part_Statements;
}
}
In the first syntax of the nested if mentioned above the
expression-1 is evaluated and the expression result is false then control
passes to statement-m. Otherwise, expression-2 is evaluated,if the condition is
true, then Nested-True-block is executed, next statement-n is also executed.
Otherwise Nested-False-Block, statement-n and statement-m are executed.
The
working procedure of the above said if..else structures are given as flowchart
below:
#include <iostream>
using namespace std;
int main()
{
int sales,
commission;
char grade;
cout <<
"\n Enter Sales amount: ";
cin >> sales;
cout <<
"\n Enter Grade: ";
cin >> grade;
if (sales > 5000)
{
commission =
sales * 0.10;
cout <<
"\n Commission: " << commission;
}
else
{
commission =
sales * 0.05;
cout <<
"\n Commission: " << commission;
}
cout <<
"\n Good Job ..... ";
return 0;
}
Enter Sales amount: 6000
Enter Grade: A
Commission: 600
Good Job .....
The
if-else ladder is a multi-path decision making statement. In this type of
statement 'if' is followed by one or more else if statements and finally end
with an else statement.
The
syntax of if-else ladder:
if (expression 1)
{
Statemet-1
}
else
if( expression 2)
{
Statemet-2
}
else
if ( expression 3)
{
Statemet-3
}
else
{
Statement-4
}
When
the respective expression becomes true, the statement associated with block is
executed, and the rest of the ladder is bypassed. If none of the conditions is
true, then the final else statement will be executed.
#include <iostream>
using namespace std;
int main ()
{
int marks;
cout<<" Enter the Marks :";
cin>>marks;
if( marks >= 60 )
cout<<
"Your grade is 1st class !!" <<endl;
else if( marks
>= 50 && marks < 60)
cout<<
"your grade is 2nd class !!" <<endl;
else
if( marks >= 40 && marks < 50)
cout<<
"your grade is 3rd class !!" <<endl;
else
cout<<
"You are fail !!" <<endl;
return 0;
}
Enter the Marks :60
Your grade is 1st class !!
When
the marks are greater than or equal to 60, the message "Your grade is 1st class !!"
is displayed and the rest of the ladder is bypassed. When the marks are
between 50 and 59, the message "Your grade is 2nd class !!"
is displayed, and the other ladder is bypassed. When the mark between 40 to 49,
the message "Your grade is 3nd
class !!" is displayed, otherwise, the message "You are fail
!!" is displayed.
The
conditional operator (or Ternary operator) is an alternative for ‘if else
statement’. The conditional operator that consists of two symbols (?:). It
takes three arguments. The control flow of conditional operator is shown below
expression
1? expression 2 : expression 3
In
the above syntax, the expression 1 is a condition which is evaluated, if the
condition is true (Non-zero), then the control is transferred to expression 2,
otherwise, the control passes to expression 3.
#include <iostream>
using namespace std;
int main()
{
int a, b, largest;
cout <<
"\n Enter any two numbers: ";
cin >> a
>> b;
largest = (a>b)? a
: b;
cout <<
"\n Largest number : " << largest;
return 0;
}
Enter any two numbers: 12 98
Largest number : 98
The
switch statement is a multi-way branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the
expression. The switch statement replaces multiple if-else sequence.
The
syntax of the switch statement is;
switch(expression)
{
case constant 1:
statement(s);
break;
case constant 2:
statement(s);
break;
.
.
.
.
default:
statement(s);
}
In
the above syntax, the expression is evaluated and if its value matches against
the constant value specified in one of the case statements, that respective set
of statementsare executed. Otherwise, the statements under the default option
are executed. The workflow of switch statement and flow chart are shown below.
1.
The expression provided in the switch should result in a constant value
otherwise it would not be valid.
2.
Duplicate case values are not allowed.
3.
The default statement is optional.
4.
The break statement is used inside the switch to terminate a statement
sequence. When a break statement is reached, the switch terminates, and the
flow of control jumps to the next line following the switch statement.
5.
The break statement is optional. If omitted, execution will continue on into
the next case. The flow of control will fall through to subsequent cases until
a break is reached.
6.
Nesting of switch statements is also allowed.
#include <iostream>
using namespace std;
int main()
{
int num;
cout <<
"\n Enter week day number: ";
cin >> num;
switch (num)
{
case 1 : cout
<< "\n Sunday"; break;
case 2 : cout
<< "\n Monday"; break;
case 3 : cout
<< "\n Tuesday"; break;
case 4 : cout
<< "\n Wednessday"; break;
case 5 : cout
<< "\n Thursday"; break;
case 6 : cout
<< "\n Friday"; break;
case 7 : cout
<< "\n Saturday"; break;
default: cout
<< "\n Wrong input....";
}
}
Enter week day number: 6
Friday
#include <iostream>
using namespace std;
int main()
{
char grade;
cout <<
"\n Enter Grade: ";
cin >> grade;
switch(grade)
{
case 'A' : cout
<< "\n Excellent...";
break;
case 'B' :
case 'C' : cout
<< "\n Welldone ...";
break;
case 'D' : cout
<< "\n You passed ...";
break;
case 'E' : cout
<< "\n Better try again ...";
break;
default : cout
<< "\n Invalid Grade ...";
}
cout << "\n Your grade is "
<< grade;
return 0;
}
Enter Grade: C
Welldone ...
Your grade is C
“if-else”
and “switch” both are selection statements. The selection statements, transfer
the flow of the program to the particular block of statements based upon
whether the condition is “true” or “false”. However, there are some differences
in their operations. These are given below:
1.
Expression inside if statement decide whether to execute the statements inside
if block or under else block. On the other hand, expression inside switch
statement decide which case to execute.
2.
An if-else statement uses multiple statements for multiple choices. On other
hand, switch statement uses single expression for multiple choices.
3.
If-esle statement checks for equality as well as for logical expression. On the
other hand, switch checks only for equality.
4.
The if statement evaluates integer, character, pointer or floating-point type
or Boolean type. On the other hand, switch statement evaluates only character
or a integer data type.
5.
Sequence of execution is like either statement under if block will execute or
statements under else block statement will execute. On the other hand the
expression in switch statement decide which case to execute and if do not apply
a break statement after each case it will execute till the end of switch
statement.
6.
If expression inside if turn out to be false, statement inside else block will
be executed. If expression inside switch statement turn out to be false then
default statements are executed.
7.
It is difficult to edit if-else statements as it is tedious to trace where the
correction is required. On the other hand, it is easy to edit switch statements
as they are easy to trace.
There
are some important things to know about switch statement. They are
1.
A switch statement can only work for quality of comparisons.
2.
No two case labels in the same switch can have identical values.
3.
If character constants are used in the switch statement, they are automatically
converted to their equivalent ASCII codes.
4.
The switch statement is more efficient choice than if in a situation that
supports the nature of the switch operation.
Tips: The switch statement is
more efficient than if-else statement.
When
a switch is a part of the statement sequence of another switch, then it is
called as nested switch statement. The inner switch and the outer switch
constant may or may not be the same.
The
syntax of the nested switch statement is;
switch (expression)
{
case constant 1:
statement(s);
break;
switch(expression)
{
case constant 1:
statement(s);
break;
case constant 2:
statement(s);
break;
.
.
.
default :
statement(s);
}
case constant 2:
statement(s);
break;
.
.
.
default :
statement(s);
}
The
below program illustrates nested switch statement example. The outer switch
checks for zero or non-zero and the inner switch checks for odd or even.
#include <iostream>
using namespace std;
int main()
{
int a = 8;
cout<<"The Number is : " <<a <<endl;
switch (a)
{
case 0 :
cout<<"The
number is zero" <<endl;
break;
default:
cout<<"The
number is a non-zero integer" <<endl;
int b = a % 2;
switch (b)
{
case 0:
cout<<"The
number is even" <<endl;
break;
case 1:
cout<<"The
number is odd" <<endl;
break;
}
}
return 0;
}
The Number is : 8
The number is a non-zero integer
The number is even
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.