[go: up one dir, main page]

0% found this document useful (0 votes)
24 views48 pages

BUE Programming Lec 3 Switch and Loops

Uploaded by

eng.sara.elmasry
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views48 pages

BUE Programming Lec 3 Switch and Loops

Uploaded by

eng.sara.elmasry
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

24CPES201 /24COMP02C

PROGRAMMING AND
LECTURE 3 SOFTWARE DESIGN
CONTROL
STRUCTURES

1
AGENDA

 Control Structures
 Selection
 If…else
 Switch
 Iteration
 While
 Do…while
 For Loop
 Types of Errors
 Syntax
 Logical
 Runtime

2
CONTROL STRUCTURES

• if … else
• switch case

3
IF AND IF-ELSE STATEMENTS

Syntax:
if(condition)  Example:

{ if(x==y)

// if body {

// Statements to execute if condition cout<<“Both numbers are equal”<<endl;


is true }
} Do I really need the braces in this example?

4
IF AND IF-ELSE STATEMENTS

 Example:
Syntax:
if(condition)
if(x==y)
{ {
// if body cout<<“Both numbers are equal”<<endl;
// Statements to execute if condition is true
}
}
else
else
{
{
cout<<“Both Numbers are not equal”<<endl;
// if body
// Statements to execute if condition is false
}
Do I really need the braces in this example?
}
5
NESTED IF AND NESTED IF-ELSE STATEMENTS
Syntax
if(condition1)
if(condition2) if(x==y)
{
if(y==z)
// if body
{
// Statements to execute if condition1 and
condition2 are true cout<<“The three numbers are equal”<<endl;
}
}
Another equivalent Code:
Another Equivalent Solution:
if(condition1 && condition2)
{ if(x==y && y==z)
// if body {
// Statements to execute if condition1 and cout<<“The three numbers are equal”<<endl;
condition2 are true 6

} }
Syntax if(x==y)
if(condition1) {
{// outer if body if(y==z)
if(condition2) {
{ cout<<“The three numbers are
// inner if body equal”<<endl;
// Statements to execute if condition1 and }
condition2 are true
else
}
{
else
cout<<“The x=y and y not equal z”<<endl;
{
}
// Statements to execute if condition1 is true and
condition2 is false }
} else
} {
else cout<<“x is not equal y”<<endl;
{ }
// Statements to execute if condition1 is false and
7

}
DANGLING ELSE  Having two if statements with only one written else and no braces

PROBLEM ➔ the else part automatically follows the inner if

8
Branching: if Statement

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

if (x == 100) equivalent if (x == 100)


cout << "x is 100"; cout << "x is 100";
cout << "x is not 100"; cout << "x is not 100";

In case x equals 100


The first block will print one message only,
9
while the second and third blocks will print two messages
Note

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

else else

cout << "x is not 100"; cout << "x is not 100";

In case x equals 100


The first block will print “x is 100”,
while the second will print “x is 100” even if x has another
value, because one symbol = means an assignment statement 10

not a comparison statement


NOTE
if (radius >= 0) if (radius >= 0)
area = radius * radius * PI; {
cout << "The area " area = radius * radius * PI;
<< " is " << area; cout << "The area "
<< " is " << area;
}
(a) Wrong (b) Correct

 Remember to include necessary braces

11
NOTE Logic Error Empty Body

if (radius >= 0); if (radius >= 0) { };


{ Equivalent {
area = radius * radius * PI; area = radius * radius * PI;
cout << "The area " cout << "The area "
<< " is " << area; << " is " << area;
} }
(a) (b)
Wrong Semicolon at the if Line
int i = 1; int i = 1;
int j = 2; int j = 2;
Equivalent
int k = 3; int k = 3;

if (i > j) if (i > j)
if (i > k) This is better if (i > k)
cout << "A"; with correct cout << "A";
else indentation else
cout << "B"; cout << "B";

(a) (b) 12

Match ELSE to correct IF (dangling else)


NOTE

To force the else clause to match the first if clause, you must add a pair of
braces:

int i = 1, j = 2, k = 3;
if (i > j)
{
if (i > k) Common Errors:
cout << "A"; • Adding semi-colon at the
end of the condition
} • Forgetting the braces for
else blocks of code.
• Dangling else.
cout << "B";
Output? 13

This statement prints B.


NOTE

if (even == true) Equivalent if (even)


cout <<"It is even."; cout << "It is even.";

(a) (b)
This is better

 Redundant Testing of Boolean Values

14
Branching: Switch Statement
Remark: Used Only for equal comparison
for integers or characters

15
A. Branching: Switch Statement (cont.)

int x=15; int x=15;


if(x==10) switch(x)
cout<<“ten\n”; {
case 10: cout<<“ten\n”;
else
break;
if(x==15) equivalent
case 15: cout<<“fifteen\n”;
cout<<“fifteen\n”; break;
else case 20: cout<<“Twenty\n”;
if(x==20) break;
cout<<“Twenty\n”; default:
else cout<<“Invalid value\n”;
}
cout<<“Invalid value\n”;

16
BRANCHING: SWITCH STATEMENT

 A toll station wants to know the vehicle type from the


user in order to decide the toll fees as follows:
 Passenger cars pay 10 LE
 Buses pay 15 LE
 Trucks pay 30 LE
 Implement a program to solve the previous problem.
 Note: You should also handle unknown vehicles by giving
them a message that they are unknown.
17
A. Branching: Switch Statement (cont.)
#include<iostream>
using namespace std;
void main()
{
float toll=-1;
char vehicle;
cout<<"Enter vehicle class ( P: Passenger, B:Bus, T:Truck)\n";
cin>>vehicle;
switch(vehicle)
{
case 'P’:
Case ‘p’:
cout<<"Passenger car\n";
toll=10;
break;
case 'B’:
Case ‘b’:
cout<<"Bus\n";
toll=15;
break;
case 'T’:
Case ‘t’:
cout<<"Truck\n";
toll=30;
break;
default: cout<<"unknown vehicle type\n";
}
18
cout<<"You should pay "<<toll<<" LE\n";
}
Branching: Switch Statement (cont.)

19
void main()
{
GRADES char grade;
INTERPRETATION cout << "Enter student grade\n";
cin >> grade;
if (grade =='A' || grade == 'a')
cout << "Excellent\n";
else if (grade =='B' || grade == 'b')
cout << "Very Good\n";
 Develop aProgram that else if (grade =='C' || grade == 'c')
reads student grade and cout << "Good\n";
interprets it. else if (grade =='D' || grade == 'd')
cout << "You can do better\n";
else if (grade =='E' || grade == 'e')
How many
branches
cout << "Disappointing\n";
execute? else
cout << "Invalid Grade\n";
}
20
GRADE INTERPRETATION

break causes switch to end and the


program continues with the first statement after
char grade; the switch structure.
cout << "Enter student grade\n";
cin >> grade;
switch (grade)
{
case 'A':
cout << "Excellent\n"; break;
case 'B':
cout << "Very Good\n"; break;
case 'C':
cout << "Good\n"; break;
case 'D':
cout << "You can do better\n"; break;
case 'E':
cout << "Disappointing\n"; break;
default:
cout << "Invalid Grade\n"; 21
}
GRADE INTERPRETATION
char grade;
cout << "Enter student grade\n";
cin >> grade;
switch (grade)
{
case 'A': // Fall to through to next case
case 'a':
cout << "Excellent\n"; break;
case 'B':
case 'b':
cout << "Very Good\n"; break;
case 'C':
case 'c':
cout << "Good\n"; break;
case 'D':
case 'd':
cout << "You can do better\n"; break;
case 'E':
case 'e':
cout << "Disappointing\n"; break;
22
default:
cout << "Invalid Grade\n";
}
PROBLEM
 Decide if input day is weekday or part of weekend based on its number.
int day;
cout << "Enter day\n";
cin >> day;
switch (day)
{
case 1: // Fall to through to the next case
case 2:
case 3:
case 4:
case 5:
cout << "Weekday\n"; break;
case 6:
case 7:
cout << "Weekend\n"; break;
default: 23
cout << "Invalid day\n";
}
CONTROL STRUCTURES

24
Design Structures
Sequence

• One statement is executed after another

Selection/Decision

• Statements can be executed or skipped depending on whether a


condition evaluates to True or False
• If – else
• switch

Repetition

• Statements are executed repeatedly until a condition evaluates to


True or False
• while
• Do…while
• for

25
CONTROL STRUCTURES

• while loop
• do….while loop
• for loop
26
WHILE LOOP
while (condition) while (condition)

{ statement;
statement1;
statement2;
}

27
Iteration: While Loop

• Its functionality is simply to repeat statements


as long as the condition is true. head: how many
times to repeat
body
while(bool_expression)
statement;
or
while(bool_expression) body: part
of code
{ statement1; that is
statement2; repeated

}
28
Iteration: While Loop (cont.)
while(bool_expression)
{ statement1; start count
if bool_exp is true
{ execute body
statement2; index update
re-evaluate bool_exp
} }
else
1 exit the loop
2

29
Iteration: While Loop (cont.)
Example

30
Iteration: While Loop (cont.)
Remark
Index update (INSIDE LOOP BODY) MUST change the result
of the bool_exp so we can exit the loop at some point of
execution, otherwise you will go into an infinite loop…
something very bad!

31
Iteration: While Loop (cont.)
Remark
Index update (INSIDE LOOP BODY) MUST change the result
of the bool_exp so we can exit the loop at some point of
execution, otherwise you will go into an infinite loop…
something very bad!

32
Iteration: While Loop (cont.)
• The body of the while statement
cannot be simple. It must be compound.
WHY?
while(bool_expression)
Because there
{ statement1; must always be
statement2; Block of code an extra
statement3; statement to
} change the
bool_expressio
n

33
1
2
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // function main begins program execution Output:
1
9 void main() 2
10 { 3
4
11 int number = 1; // initialization 5
6
12 7
13 while (number <= 10 ) { // repetition condition 8
9
14 cout << number << endl; // display number 10
15 ++number; // increment
16
17 } // end while
18
34
19
21 } // end function main
WHILE LOOP: COUNT DOWN

Program counts down from a user input value to 1 then prints FIRE!
int num;
cout << "Enter start number:\n";
cin >> num;
while (num > 0) // while (num >= 1)
{
cout << num << '\t';
num--;
}
cout << "FIRE!!\n";

35
CLASS AVERAGE (5 STD.)

int total; // sum of grades


int gradeCounter; // number of grades to be entered
int grade; // grade value
int average; // average of grades

total = 0; // initialize total


gradeCounter = 1; // initialize loop counter

while (gradeCounter <= 5) //loop 5 times


{
cout << "Enter grade: "; // prompt for input
cin >> grade; //read grade from user
total = total + grade; // add grade to total
gradeCounter++; // increment counter
}
average = total / 5;
36
cout << "Class average is " << average << endl;
HOW TO DISPLAY CORRECT AVERAGE?

float total;
int gradeCounter;
int grade;
float average;

total = 0;
gradeCounter = 1;

while (gradeCounter <= 5)


{
cout << "Enter grade: "; Another Solution:
cin >> grade;
total = total + grade; int total; Type
Casting
gradeCounter = gradeCounter + 1; float average;
}
……….
average = total / 5;
cout << "Class average is " << average << endl; ……..
average= (float) total/5;
37
38
PROBLEM

 Suppose that the tuition for a university is $10,000 this year and
that the tuition increases 7% every year. In how many years will the
tuition be doubled or more?

39
SOLUTION

int year = 1;
float tuition = 10000; // Year 1
while (tuition < 20000)
{
year++;
tuition *= 1.07; //tuition = tuition + tuition * 0.07

cout << "Tuition will be doubled in " << year << " years" << endl;
cout << "Tuition will be $" << tuition << " in "
<< year << " years" << endl;

40
DO WHILE LOOP

do do
statement; {
while (condition); statement1;
statement2;
} while (condition);

Its functionality is simply to execute set of statements


and then repeat them as long as the condition is
true.
41
Iteration: Do..While Loop
do
Notice the
{ statement1; semicolon

statement2;
} while(bool_expression) ;
body: part
of code
that is
repeated

head: how many


times to repeat
body
42
Iteration: Do..While Loop (cont.)
do
{ statement1; start count
{ execute body
index update
statement2; re-evaluate bool_exp
} if bool_exp is true
} while(bool_expression);
else
1 exit the loop

Compared to the while loop


2

43
Iteration: Do..While Loop (cont.)
What if i is
initialized

Example1: by 3?

44
1 // Fig. 2.24: fig02_24.cpp
2 // Using the do/while repetition structure.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // function main begins program execution
9 void main()
10 {
11 int counter = 1; // initialize counter
12
13 do {
14 cout << counter << " "; // display counter
15 } while ( ++counter <= 10 ); // end do/while
16
Notice the preincrement
17 cout << endl; in loop-continuation test.
18
19
20
21 } // end function main 45

1 2 3 4 5 6 7 8 9 10
int num;
cout << "Enter start number:\n";
DO
cin >> num;
WHILE:
do
COUNT
{ DOWN
cout << num << '\t';
num--;
} while (num > 0);
cout << "FIRE!!\n"; 46
47
48

You might also like