Control Structure - If Else and Switch in C++ Programming
Control Structure - If Else and Switch in C++ Programming
LECTURE # 4: CONTROL
STRUCTURE - A
BSE 1
Joddat Fatima
1
joddat.fatima@gmail.com
Department of C&SE
Bahria University Islamabad
CONTROL STRUCTURE
For that purpose, C++ provides control structures that serve to specify
what has to be done by our program, when and under which
circumstances.
Sequence structure
Programs executed sequentially by default
Selection structures
if, if/else, switch
Repetition structures
while, do/while, for
3
SELECTION STRUCTURE IF-ELSE
4
IF STRUCTURE
5
CONDITIONAL -- IF
7
IF AND ELSE STRUCTURE
if
Performs action if condition true
if/else
Different actions if conditions true or false
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
Prints on the screen x is 100 if indeed x has a value of 100, but if it has not 8
-and only if not- it prints out x is not 100.
EXAMPLE IF AND ELSE
9
NESTED IF ELSE
The if + else structures can be concatenated with the intention of verifying a range of
values.
One inside another, test for multiple cases
Once condition met, other statements skipped
The following example shows its use telling if the value currently stored in x is
positive, negative or none of them (i.e. zero):
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";
Remember that in case that we want more than a single statement to be executed, we 10
must group them in a block by enclosing them in braces { }.
FLOW DIAGRAM IF-ELSE
11
EXAMPLE NESTED IF AND ELSE
12
SELECTION STRUCTURE SWITCH
13
SWITCH STRUCTURE
Something similar to what we did at the beginning of this section with the
concatenation of several if and else if instructions.
14
SWITCH FLOW DIAGRAM
15
THE CONTROLLING STATEMENT
16
THE BREAK STATEMENT
17
THE DEFAULT STATEMENT
18
EXAMPLE SWITCH
19
EXAMPLE SHOW BOTH SELECTIVE STRUCTURES
20
EXAMPLES
21
EXAMPLE # 1
#include <iostream>
int main()
{
int number;
cout << "Enter Number\n";
cin >> number;
if(num%2==0)
cout <<“NUMBER IS EVEN”<<endl;
else
cout <<“NUMBER IS ODD”<<endl;
return 0;
}
22
EXAMPLE # 2
23
EXAMPLE # 3
int main()
{
double number1, number2, number3;
cout << "Enter three floating-point numbers: ";
cin >> number1 >> number2 >> number3;
double max = number1;
25
EXAMPLE # 5
26
EXAMPLE # 6
27