Professional Documents
Culture Documents
Lecture 3 Control Structures Selection Statements 07032023 103638am
Lecture 3 Control Structures Selection Statements 07032023 103638am
Lecture 3 Control Structures Selection Statements 07032023 103638am
LECTURE
Abrar Ahmed
abrarahmed.buic@bahria.edu.pk
Outline
• if statement
• Use of if else
• else-if Statement
• Switch statement
1
3/7/2023
Control Structures
• 3 control structures
(Bohm and Jacopini Theorem)
• Sequence structure
• Executing one subprogram, and then another subprogram (sequence)
2
3/7/2023
Control Structures
• 3 control structures
• Sequence structure
• Programs executed sequentially by default
• Selection structures
• If (Single Selection Statement)
• if/else (Double Selection Statement)
• switch (Multiple Selection Statement)
• Repetition structures
• For
• While
• do/while
Control Structures
3
3/7/2023
Selection Structures
4
3/7/2023
if Statement
• C++ uses keyword if to implement the decision control instruction.
if ( this condition is true )
execute this statement;
• If the condition is true than compiler will execute the immediate statement. But if the condition is false
than the immediate statement will not execute, and the compiler will skip the immediate statement and
execute the next statement.
10
5
3/7/2023
11
12
6
3/7/2023
if Statement Example
int main ( )
{
int x;
cout<<“Enter a number”;
cin>> x;
if ( x > 100 )
cout<<“the number is greater than 100”;
return 0;
}
13
Example
14
7
3/7/2023
• if
• Performs action if condition true
• if/else
• Different actions if conditions true or false
• Pseudocode
if student’s grade is greater than or equal to 60
print “Passed”
else
print “Failed”
• C++ code
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
15
if-else Example
#inlcude<iostream>
using namespace std;
int main ()
{
int num;
cout<<"Enter any number\n";
cin>>num;
if (num>0)
cout<<“The number you entered is positive\n”;
else
cout<<“The number you entered is negative\n”;
return 0;
}
16
8
3/7/2023
So this means!!
if ( TRUE )
{
// Execute these statements if TRUE
}
else
{
// Execute these statements if FALSE
}
17
• Compound statement
• Set of statements within a pair of braces
if ( grade >= 60 )
cout << "Passed.\n"; Statement1;
else
Statement2;
{
cout << "Failed.\n"; Statement3;
cout << "You must take this course again.\n";
}
• Without braces,
cout << "You must take this course again.\n";
always executed
• Block
• Set of statements within braces
18
9
3/7/2023
Example
19
20
10
3/7/2023
Example
if ( grade >= 90 ) // 90 and above
cout << "A";
else if ( grade >= 80 ) // 80-89
cout << "B";
else if ( grade >= 70 ) // 70-79
cout << "C";
else if ( grade >= 60 ) // 60-69
cout << "D";
else // less than 60
cout << "F";
21
else..if example
int main ( )
{ int month;
cout<<“ Enter Month in Number= ”
cin>>month;
if ( month == 1 )
cout<<“ January”;
else if ( month == 2 )
cout << “ February ”;
else if ( month == 3 )
cout<< “ March ”;
:
else
cout << “ December ”;
return 0;
}
22
11
3/7/2023
if(even == 0) { do something }
23
if (x > 0)
num_pos = num_pos + 1;
if (x < 0)
num_neg = num_neg + 1;
if (x == 0)
num_zero = num_zero +1;
24
12
3/7/2023
if(x > 0)
num_pos = num_pos + 1;
else if(x < 0)
num_neg = num_neg + 1;
else
num_zero = num_zero + 1;
25
if ( condition_1 )
statement_1
else if ( condition_2 )
statement_2
.
.
.
else if ( condition_n )
statement_n
else
statement_e
26
13
3/7/2023
27
28
14
3/7/2023
false true
grade >= 60
29
Conditional Operator
30
15
3/7/2023
Example
int x, y;
cin>>x;
y = (x>5 ? 3 : 4);
cout<< y;
31
int i;
cin>> i;
(i==1 ? cout<<“ hello < 1”: cout<<“hello world != 1”);
• The conditional operators can be nested as shown below
int k, num = 30;
k=(num>5 ? (num <=10 ? 100 : 200) : 500);
cout<< k;
• The limitation of the conditional operator is that after the ? Or after the : only one C++ statement can
occur.
32
16
3/7/2023
Switch Statement
33
34
17
3/7/2023
Switch Statement
• If you have a large decision tree, and all the decisions depend on the value of the same variable, switch statement is suitable instead of
if..else or else..if statement.
switch ( integer expression )
{
case constant_1:
statement(s);
case constant_2:
statement(s);
:
:
case constant_n:
statement(s);
default:
statement;
}
CSC 113 – Computer Programming
Department of Computer Sciences
3. Control Structures
Bahria University, Islamabad
Slide: 35
35
switch (choice) {
case 1 : do_option_one(); break;
case 2 :
case 3 : do_2_3_a ();
do_2_3_b (); break;
default : do_something_else (); }
• Value of the switch expression matched with one of the labels attached
to a branch
switch (choice) {
case 1 : do_option_one(); break;
case 2 :
case 3 : do_2_3_a ();
do_2_3_b (); break;
default : do_something_else (); }
36
18
3/7/2023
switch Structures
• Switch expression => the expression in parentheses whose value determines which switch label is
selected
• cannot be floating point
• usually is int or char
• Identifiers
following case
must be constants
switch (choice) {
case 1 : do_option_one(); break;
case 2 :
case 3 : do_2_3_a ();
do_2_3_b (); break;
default : do_something_else (); }
37
Switch Statement
• The integer expression following the keyword switch is an expression that will yield an integer value. It could
be an integer constant like 1, 2,or 3, or an expression that evaluates to an integer.
• The keyword case is followed by an integer or a character constant. The constant in each case must be
different from other.
38
19
3/7/2023
Example
int main ( )
{
int i = 2;
switch (i)
{
case 1:
cout<<“case 1 \n”;
case 2:
cout<<“case 2 \n”;
case 3:
cout<<“case 3 \n”;
default:
cout<<“default \n”;
} Output of the program
return 0;
} Case 2
Case 3
default
39
switch Structures
• The break causes control to be shifted to first statement after the switch statement
• The default statement is executed if the value of the switch expression is NOT found among switch labels
switch (choice) {
case 1 : do_option_one();
break;
case 2 :
case 3 : do_2_3_a ();
do_2_3_b ();
break;
default : do_something_else
();
}
// next statement
40
20
3/7/2023
Break Statement
• If we want that only particular case should be executed then break statement should be used to get out of
the control structure.
int i = 2;
switch (i)
{
case 1:
cout<<“case 1 \n”;
break;
case 2:
cout<<“case 2 \n”;
break;
case 3:
cout<<“case 3 \n”;
break;
default:
cout<<“default \n”;
}
41
b) You are also allowed to use char values in case and switch.
c) You can write a case in switch, which is not followed by any statement. As shown in the next example
42
21
3/7/2023
char ch;
cin>>ch
switch(ch)
{
case ‘a’:
case ‘A’:
cout<<“you entered a”;
break;
case ‘b’:
case ‘B’:
cout<<“you entered b”;
break;
case ‘c’:
case ‘C’:
cout<<“you entered c”;
}
43
h) In principle, a switch may occur within another, but in practice it is rarely done.
i) The switch statement is very useful while writing menu driven programs.
44
22
3/7/2023
Example
char character; char character;
cout << "Enter a character : "; cout << "Enter a character : ";
cin >> character;
cin >> character; switch (character)
switch (character) {
{ case 'a’:
case 'a’: case ‘A’:
cout << " Australia " << endl; cout << " Australia " << endl;
cout << " Afaghanistan " << endl;
break; break;
case 'b': case 'b’:
cout << " Bangladesh " << endl; case ‘B’:
break; cout << " Bangladesh " << endl;
case 'c': break;
case 'c’:
cout << " Chille " << endl; case ‘C’:
break; cout << " Chille " << endl;
case 'd': break;
cout << " Denmark " << endl; case 'd’:
break; case ‘D’:
cout << " Denmark " << endl;
case 'e': break;
cout << " England " << endl; case 'e’:
break; case ‘E’:
case 'f': cout << " England " << endl;
cout << " France " << endl; break;
case 'f’:
break; case ‘F’:
case 'g': cout << " France " << endl;
cout << " Gana " << endl; break;
break; case 'g’:
default: case ‘G’:
cout << " Gana " << endl;
cout << " I dont know more countries " << endl; break;
} default:
cout << " I dont know more countries " << endl;
}
CSC 113 – Computer Programming
Department of Computer Sciences
3. Control Structures
Bahria University, Islamabad
Slide: 45
45
Example
switch (character)
{
case 'a':
area = 3.14f * radius * radius;
cout << " Area = " << area << endl;
break;
case 'c':
circum = 2 * radius * 3.14f;
cout << " Circumference = " << circum << endl;
break;
default: cout << " Invalid letter was read " << endl;
}
46
23
3/7/2023
cout << "Enter the grade of student : "; cin >> character;
switch (character)
{
case 'A':
case 'a':
cout << "Excellent";
break;
case 'B':
case 'b':
cout << "Good";
break;
case 'C':
case 'c':
cout << "O.K";
break;
case 'D':
case 'd':
case 'F':
case 'f':
cout << "poor";
break;
default: cout << "invalid letter grade";
}
47
Example
48
24
3/7/2023
49
If ( grade >=90)
cout<<“A”;
If ( grade >=80)
cout<<“B”;
If ( grade >=70)
cout<<“C”;
If ( grade > =60)
cout<<“D”;
If ( grade<60)
cout<<“F”;
CSC 113 – Computer Programming
Department of Computer Sciences
3. Control Structures
Bahria University, Islamabad
Slide: 50
50
25
3/7/2023
51
true
case a case a action(s) break
false
true
case b case b action(s) break
false
.
.
.
true
case z case z action(s) break
false
default action(s)
52
26
3/7/2023
Example
53
Example
54
27
3/7/2023
Example
/* Determines the class of Ship given its class ID */
void main(void) {
char classID;
switch (classID) {
case 'B':
case 'b':
cout<<"Battleship”<<endl;
break;
case 'C':
case 'c':
cout<<"Cruiser" <<endl;
break;
case 'D':
case 'd':
cout<< "Destroyer"<< endl;
break;
default:
cout<< “Unknown class” << endl;
}
return 0;
}
CSC 113 – Computer Programming
Department of Computer Sciences
3. Control Structures
Bahria University, Islamabad
Slide: 55
55
Exaplanation of Example
• This takes the value of the variable classID and compares it to each of the cases in a top down approach.
• It stops after it finds the first case that is equal to the value of the variable class.
• It then starts to execute each line of the code following the matching case till it finds a break statement or
the end of the switch statement.
• If no case is equal to the value of class, then the default case is executed.
• default case is optional. So if no other case is equal to the value of the controlling expression and there is a
default case, then default case is executed. If there is no default case, then the entire switch body is skipped
• The statements following a case label may be one or more C statements, so you do not need to make
multiple statements into a single compound statement using braces.
• It is important to remember that type int and char values may be used as case labels, type double values
cannot be used.
• Another very common error is the omission of the break statement at the end of one alternative.
• In such a situation, execution ”falls through” into the next alternative.
• Forgetting the closing brace of the switch statement body is also easy to do.
CSC 113 – Computer Programming
Department of Computer Sciences
3. Control Structures
Bahria University, Islamabad
Slide: 56
56
28
3/7/2023
If versuses switch
• Advantages of if:
• It is more general than a switch
• It can be a range of values such as x < 100
• A switch can not compare doubles
• Advantages of switch:
• A switch is more readable
57
58
29
3/7/2023
59
Multiple Selections
• Contrast
• A sequence of
if … else if … statements
• What happens in each case when it is the first if condition that is true?
• if … else if sequence will jump out of the structure whenever match is found
• sequence of separate if's – each if is checked, no mater where the match is
60
30
3/7/2023
61
62
31
3/7/2023
Example
• Write a program that takes a character from user and prints if the character is vowel or consonant.
63
Example
char myChar;
cout << "Enter an Alphabet : ";
cin >> myChar;
else if ((myChar >= 97 && myChar <= 122) || (myChar >= 65 && myChar <= 90))
{
if (myChar == 'a' || myChar == 'e' || myChar == 'i' || myChar == 'o' || myChar ==
'u' || myChar == 'A' || myChar == 'E' || myChar == 'I' || myChar == 'O' || myChar ==
'U’)
cout << "You have entered a VOWEL";
else
cout << "You have entered a CONSONANT";
}
else
cout << "ERROR!!\nYou did not enter an Alphabet";
64
32
3/7/2023
Example
int myNumber;
cout << "Enter a Postive Number : ";
cin >> myNumber;
if (myNumber > 0)
{
if (myNumber % 2 == 0)
{
cout << "Number is EVEN number " << endl;
}
else
cout << "Number is ODD number " << endl;
}
else
{
cout << "You have entered a -ve number " << endl;
}
65
Activity
• Create the equivalent of a four-function calculator. The program should ask the user to enter a number, an
operator, and another number. (Use floating point.) It should then carry out the specified arithmetical
operation: adding, subtracting, multiplying, or dividing the two numbers. Use a switch statement to select
the operation. Finally, display the Result.
• Some sample interaction with the program might look like this:
Enter first number, operator, second number: 12 + 100
Answer = 112
66
33
3/7/2023
Task 1
• Write a temperature-conversion program that gives the user the option of converting Fahrenheit to Celsius
or Celsius to Fahrenheit. Then carry out the conversion. Use floating-point numbers. Interaction with the
program might look like this:
°C x 9/5 + 32 = °F
(°F - 32) x 5/9 = °C
67
34