C++ Decision Making Statements: Lecture Three
C++ Decision Making Statements: Lecture Three
statements
Lecture three
decision making statements
Sometimes we need to execute a block of
statements only when a particular condition is
met or not met. This is called decision making,
as we are executing a certain code after making
a decision in the program logic. For decision
making in C++,
C++ decision making statements
Decision making structures require that the
programmer specify one or more conditions to be
evaluated or tested by the program, along with a
statement or statements to be executed if the
condition is determined to be true, and optionally,
other statements to be executed if the condition is
determined to be false.
Following is the general form of a typical decision making
structure found in most of the programming languages −
C++ programming language provides
following types of decision making
statements.
if statement
if...else statement
nested if statements
switch statement
If statement in C++
if(condition){
Statement(s);
}
If statement in C++(Cont’..)
if(condition)
{
Statement(s);
}
else
{
Statement(s);
}
If else statement in C++
if(boolean_expression 1) {
// Executes when the boolean expression 1 is true
} else if( boolean_expression 2) {
// Executes when the boolean expression 2 is true
} else if( boolean_expression 3) {
// Executes when the boolean expression 3 is true
} else {
// executes when the none of the above condition is
true.
}
Nested if statement in C++
When there is an if statement inside another if
statement then it is called the nested if statement.
The structure of nested if looks like this:
if(condition_1) {
Statement1(s);
if(condition_2) {
Statement2(s);
}
}
Switch Case statement in C++
with example
Switch case statement is used when we have multiple
conditions and we need to perform different action based
on the condition. When we have multiple conditions and
we need to execute a block of statements when a
particular condition is satisfied. In such case either we can
use lengthy if..else-if statement or switch case. The
problem with lengthy if..else-if is that it becomes complex
when we have several conditions.
The switch case is a clean and efficient method of
handling such scenarios.
The syntax of Switch
case statement:
The syntax for a switch statement in C++ is as follows −
switch(expression) {
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional