Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Lab Session 07

Control Structures, Decision Making using simple If, If-Else statement.

Objectives:
1. To understand Control Structures,

2. Demonstration of decision Making using simple If, If-Else statement.


3. Design and Compilation of C++ programs based on decision making.

Algorithms
Any solvable computing problem can be solved by executing of a series of actions in a specific
order. A procedure for solving a problem in terms of 1. the actions to execute and 2. the order in
which the actions execute is called an algorithm. The following example demonstrates that
correctly specifying the order in which the actions execute is important. Consider the “rise-and-
shine algorithm” followed by one junior executive for getting out of bed and going to work:

Control Structures.
A program is usually not limited to a linear sequence of instructions. During its process it may
bifurcate, repeat code or take decisions. For that purpose, C++ provides control structures that
serve to specify what has to be done to perform our program.
With the introduction of control sequences we are going to have to introduce a new concept:
the block of instructions. A block of instructions is a group of instructions separated by semicolons
(;) butgrouped in a block delimited by curly bracket signs: { and }.
Most of the control structures that we will see in this section allow a generic statement as a
parameter, this refers to either a single instruction or a block of instructions, as we want. If we
want the statement to be a single instruction we do not need to enclose it between curly-brackets
({}). If we want the statement to be more than a single instruction we must enclose them between
curly brackets ({}) forming a block of instructions.

Conditional structure: if and else

62
It is used to execute an instruction or block of instructions only if a condition is fulfilled. Its form
is:

if (condition) statement

where condition is the expression that is being evaluated. If this condition is true, statement is
executed. If it is false, statement is ignored (not executed) and the program continues on the next
instruction after the conditional structure.

For example, the following code fragment prints out x is 100 only if the value stored in
variable x is indeed 100:

if (x == 100)
cout << "x is 100";

If we want more than a single instruction to be executed in case that condition is true we can
specify a block of instructions using curly brackets { }:
if (x == 100)
{
cout << "x is ";
cout << x;
}

We can additionally specify what we want that happens if the condition is not fulfilled by using
the keyword else. Its form used in conjunction with if is:

if (condition) statement1 else statement2

For example:

if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";

prints out on the screen x is 100 if indeed x is worth 100, but if it is not -and only if not- it prints
out x is not 100.

The if + else structures can be concatenated with the intention of verifying a range of values.
The following example shows its use telling if the present value stored in x is positive, negative
or none of the previous, that is to say, equal to zero.

if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";

63
else
cout << "x is 0";

Remember that in case we want more than a single instruction to be executed, we must group
them in a block of instructions by using curly brackets { }.

Decisions
The decisions in a loop always relate to the same question: Should we do this (the loop body)
again?
Programs also need to make these one-time decisions. In a program a decision causes a onetime
jump to a different part of the program, depending on the value of an expression.
Decisions can be made in C++ in several ways. The most important is with the if...else statement,
which chooses between two alternatives. This statement can be used without the else, as a simple
if statement. Another decision statement, switch, creates branches for multiple alternative sections
of code, depending on the value of a single variable. Finally, the conditional operator is used in
specialized situations. We’ll examine each of these constructions.

The if Statement

The if statement is the simplest of the decision statements. Our next program, IFDEMO,
provides
an example.

// ifdemo.cpp
// demonstrates IF statement
#include <iostream>
using namespace std;
int main()
{
int x;
cout << “Enter a number: “;
cin >> x;
if( x > 100 )
cout << “That number is greater than 100\n”;
return 0;
}

64
The if keyword is followed by a test expression in parentheses. The syntax of the if statement is
shown in Figure 3.7. As you can see, the syntax of if is very much like that of while. The
difference is that the statements following the if are executed only once if the test expression is
true; the statements following while are executed repeatedly until the test expression becomes
false. Figure 3.8 shows the operation of the if statement.

Here’s an example of the IFDEMO program’s output when the number entered by the user is
greater than 100:
Enter a number: 2000
That number is greater than 100
If the number entered is not greater than 100, the program will terminate without printing the
second line.

Syntax of if-statement:

Operation of if-statement:

65
Multiple Statements in the if Body

As in loops, the code in an if body can consist of a single statement—as shown in the IFDEMO
example—or a block of statements delimited by braces. This variation on IFDEMO, called IF2,
shows how that looks.

#include <iostream>
using namespace std;
int main()
{
int x;
cout << “Enter a number: “;
cin >> x;
if( x > 100 )
{
cout << “The number “ << x;
cout << “ is greater than 100\n”;
}
return 0;
}
Here’s some output from IF2:
Enter a number: 12345
The number 12345 is greater than 100

66
The if...else Statement
The if statement lets you do something if a condition is true. If it isn’t true, nothing happens. But
suppose we want to do one thing if a condition is true, and do something else if it’s false. That’s
where the if...else statement comes in. It consists of an if statement, followed by a statement or
block of statements, followed by the keyword else, followed by another statement or block of
statements. The syntax is shown in Figure.

#include <iostream>
using namespace std;

int main()
{
int x;
cout << “\nEnter a number: “;
cin >> x;
if( x > 100 )
cout << “That number is greater than 100\n”;
else
cout << “That number is not greater than 100\n”;
return 0;
}

Syntax of if-Else statement:

Operation of if-Else statement:

67
Lab task
1. Write a program whether an interger entered is positive or negative number entered by
the user.
2. Write a program that takes students marks from user, if the obtained marks is less than 60
prints “Fail” otherwise “Pass”.
Post lab task
1-What is PseudoCode
2- Write a temperature-conversion program that gives the user the option of convertingFahrenheit
to Celsius or Celsius to Fahrenheit. Then carry out the conversion. Usefloating-point numbers.
Interaction with the program might look like this:
Type 1 to convert Fahrenheit to Celsius,
2 to convert Celsius to Fahrenheit: 1
Enter temperature in Fahrenheit: 70
In Celsius that’s 21.111111

68
Decision Making with Switch structure and Comparison with If-else
statement
Objectives:
1. Demonstration of Decision Making with Switch structure

2. Analyze switch structure with If-else statement


3. Design and Compilation of C++ programs using switch statement.

Switch Statements:
Switch statement falls in the category of selection statements like if and else. C++ provides three
types of selection statements. The if selection statement either performs (selects) an action if a
condition is true or skips the action if the condition is false. The if…else selection statement
performs an action if a condition is true or performs a different action if the condition is false.

The switch selection statement performs one of many different actions, depending on the value of
an integer expression. The switch selection statement is called a multiple-selection statement
because it selects among many different actions (or groups of actions). Each action is associated
with the value of a constant integral expression (i.e., any combination of character and integer
constants that evaluates to a constant integer value).

If you have a large decision tree, and all the decisions depend on the value of the same variable,
you will probably want to consider a switch statement instead of a ladder of if...else or else if
constructions. Here’s a simple example:

// demonstrates SWITCH statement

#include <iostream>
using namespace std;
int main()
{
int speed; // speed
cout << “\nEnter 80, 120, or 130 : “;
cin >> speed; //user enters speed
switch(speed) //selection based on speed
{
case 80: //user entered 80
cout << “ Highway Normal Speedn”;
break;
case 120: //user entered 120
cout << “High Speed\n”;
break;
case 130: //user entered 130
cout << “Over Speed\n”;

69
break;
}
return 0;
}

This program prints one of three possible messages, depending on whether the user inputs the
number 80, 120, or 130 then displays message associated w.r.t. speed.

The keyword switch is followed by a switch variable in parentheses.

switch(speed)

Syntax of the switch statement:

Syntax of the switch statement


Before entering the switch, the program should assign a value to the switch variable. This value
will usually match a constant in one of the case statements. When this is the case (pun intended!),
the statements immediately following the keyword case will be executed, until a break is reached.

The break Statement:

70
Above program has a break statement at the end of each case section. The break keyword causes
the entire switch statement to exit. Control goes to the first statement following the end of the
switch construction, which is the end of the program. Don’t forget the break; without it, control
passes down (or “falls through”) to the statements for the next case, which is usually not what you
want (although sometimes it’s useful).

If the value of the switch variable doesn’t match any of the case constants, control passes to the
end of the switch without doing anything. The operation of the switch statement is shown in Figure
below.

Operation of the switch statement

Important Points about Switch Case Statements:

71
1. The expression provided in the switch should result in a constant
value otherwise it would not be valid.
Valid expressions for switch:
// Constant expressions allowed
switch(1+2+23)
switch(1*2+3%4)
Invalid switch expressions for switch:
// Variable expression not allowed
switch(ab+cd)
switch(a+b+c)

2. Duplicate case values are not allowed.


3. The default statement is optional.Even if the switch case statement do not have a
default statement, it would run without any problem.
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 are allowed, which means you can have switch
statements inside another switch. However nested switch statements should be
avoided as it makes program more complex and less readable.

The default Keyword:

In the ADSWITCH program, where you expect to see the last case at the bottom of the switch
construction, you instead see the keyword default. This keyword gives the switch construction a
way to take an action if the value of the loop variable doesn’t match any of the case constants.
Here we use it to print Try again if the user types an unknown character. No break is necessary
after default, since we’re at the end of the switch anyway.

switch statement is a common approach to analyzing input entered by the user. Each of the possible
characters is represented by a case. It’s a good idea to use a default statement in all switch
statements, even if you don’t think you need it. A construction such as default:

cout << “Error: incorrect input to switch”; break;


It alerts the programmer (or the user) that something has gone wrong in the operation of the
program. In the interest of brevity we don’t always include such a default statement, but you
should, especially in serious programs.

72
Example: Program to built a simple calculator using switch Statement

// Program to built a simple calculator using switch Statement


#include <iostream>
using namespace std;

int main()
{
char o;
float num1, num2;

cout << "Enter an operator (+, -, *, /): ";


cin >> o;

cout << "Enter two operands: ";


cin >> num1 >> num2;

switch (o)
{
case '+':
cout << num1 << " + " << num2 << " = " << num1+num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1-num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1*num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1/num2;
break;

73
default:
// operator is doesn't match any case constant (+, -, *, /)
cout << "Error! operator is not correct";
break;
}

return 0;
}

Output:

Enter an operator (+, -, *, /): +

Enter two operands: 2.3

4.5

2.3 - 4.5 = -2.2

The - operator entered by the user is stored in o variable. And, two operands 2.3 and 4.5 are stored in
variables num1 and num2 respectively.Then, the control of the program jumps to

cout << num1 << " - " << num2 << " = " << num1-num2;Finally, the break statement
ends the switch statement.If break statement is not used, all cases after the correct case is executed.

Example: Program that displays grade

#include <iostream>

74
using namespace std;

int main () {

// local variable declaration:

char grade = 'D';

switch(grade) {

case 'A' :

cout << "Excellent!" << endl;

break;

case 'B' :

case 'C' :

cout << "Well done" << endl;

break;

case 'D' :

cout << "You passed" << endl;

break;

case 'F' :

cout << "Better try again" << endl;

break;

default :

cout << "Invalid grade" << endl;

cout << "Your grade is " << grade << endl;

return 0;

75
This would produce the following result −
You passed
Your grade is D

SWITCH versus if-else

When do you use a series of if...else (or else if) statements, and when do you use a switch
statement? In an else if construction you can use a series of expressions that involve unrelated
variables and are as complex as you like.

Both of the following code fragments have the same behavior, demonstrating the if-else equivalent
of a switch statement:

For example:

You are having trouble following the logic of the switch statement, it is essentially the same as
writing an if statement for each case statement:
For example:

if ( 1 == input )
{
playgame();
}
else if ( 2 == input )
{
loadgame();
}
else if ( 3 == input )
{
playmultiplayer();
}
else if ( 4 == input )
{
cout << "Thank you for playing!\n";
}
else
{
cout << "Error, bad input, quitting\n";
}

76
If we can do the same thing with an if/else, why do we need a switch at all? The main advantage
of the switch is that it’s quite clear how the program flow works: a single variable controls the
code path. With a series of if/else conditions, each condition needs to be carefully read.

Lab task
1-Write a C program to find roots of a quadratic equation using switch case.
2-Write a C program to check whether an alphabet is vowel or consonant using switch case.

Post lab task


1-Write a C program to check whether a number is positive, negative or zero using switch case.

Assignment:

1. What is The getche() Library Function.


2. Elaborate ‘continue’ statement used in C++.
3. Write C++ statements to find vowels.

77
78

You might also like