0% found this document useful (0 votes)
2 views

C++ Lecture Four

The document discusses programming fundamentals, focusing on control structures, particularly selection statements in algorithmic languages and C++. It covers one-way, two-way, and multi-way selections, along with increment and decrement operators in C++. Several examples illustrate how to implement these concepts in algorithms and C++ code.

Uploaded by

Ahmed Al-nasheri
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)
2 views

C++ Lecture Four

The document discusses programming fundamentals, focusing on control structures, particularly selection statements in algorithmic languages and C++. It covers one-way, two-way, and multi-way selections, along with increment and decrement operators in C++. Several examples illustrate how to implement these concepts in algorithms and C++ code.

Uploaded by

Ahmed Al-nasheri
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/ 61

dfdfdfdfdfdfddfdfdf

Programming Fundamentals

Control Structures
(Selections)

Dr. Ahmed Alnasheri 11/27/2020

Programming Fundamentals (Lecture Four) 1


Content

Topics to cover here:

Selection statements in the algorithmic language:


:‫عبارات االختيار في لغة الخوارزمية‬

◼ One-Way Selection ‫اختيار أحادي االتجاه‬


◼ Two-Way Selection ‫اختيارثنائي االتجاه‬
◼ Multi-Way Selection ‫اختيار متعدد االتجاه‬
◼ Nested Structures ‫الهياكل المتداخلة‬
◼ Selection statements in C++ language
Programming Fundamentals (Lecture Four) 2
Increment and Decrement Operators in C++
‫معامل اإلسناد البسيط‬ ‫معامل اإلسناد المركب‬
Simple assignment operator Compound assignment operator
X = X + 1; X += 1;
Y=Y–1; Y -= 1 ;
Z=Z+X; Z += X ;
P = P * item ; P *= item ;
N = N * (x + 1) ; N *= (x + 1) ;
Total = Total / (X+Y); Total /= (X+Y);
Hours = Hours % 13; Hours %= 13;

Programming Fundamentals (Lecture Four) 3


Increment and Decrement Operators in C++
Increment Operators (‫ )عامل الزيادة‬Decrement Operators(‫)عامل النقص‬
1- Postfix operator: e.g. i++ 1- Postfix operator: e.g. i--
2- Prefix operator: e.g. ++i 2- Prefix operator: e.g. --i
• For postfix operators, the increment (or decrement) occurs after the current value
of the variable has been used.
.‫ تحدث الزيادة (أو التناقص) بعد استخدام القيمة الحالية للمتغير‬،‫• بالنسبة إلى معامالت الالحقة‬
• For prefix operators, the increment (or decrement) occurs first and the new value
of the variable is then used.
.‫ تحدث الزيادة (أو التناقص) أوالً ثم يتم استخدام القيمة الجديدة للمتغير‬، ‫• بالنسبة لمعامالت البادئة‬
• Example
The following C++ statements has the effects as shown in the comment:
i = 3; // initial value of i
k = i++; // assigns 3 to k and 4 to i
k = ++i; // assigns 5 to k and 5 to i
k = i-- ; // assigns 5 to k and 4 to i
k = --i ; // assigns 3 to k and 3 to i

Programming Fundamentals (Lecture Four) 4


Increment and Decrement Operators
Simple easy easiest

x = x+1; x += 1 x++

x = x-1; x -= 1 x--

◼ Example
◼ Compute the following expression where: z=3, x=2, y=2
‫احسب التعبير التالي حيث‬ ◼
z+= ++x - y--;
Solution:
z=4?

Programming Fundamentals (Lecture Four) 5


Selections

◼ The selection statement allows to choose a set of


statements for execution.
.‫يسمح بيان االختيار باختيار مجموعة من العبارات للتنفيذ‬ ▪

◼ The selection depends on the validity of a condition


when the program is executed.
.‫يعتمد االختيار على صحة الشرط عند تنفيذ البرنامج‬ ▪

◼ The condition is a logical expression that has values


as true or false.
.‫الشرط هو تعبير منطقي له قيم مثل صواب أوخطأ‬ ▪

Programming Fundamentals (Lecture Four) 6


One-Way Selection
Syntax:

In pseudo code In C++


IF (condition) THEN if (logical expression)
statements statements;
END IF

The semantics (execution) of this statement:


-If the value of the “condition” is true, the statements between IF .. END IF
are executed and the execution continues to the statement after END IF.
-If the value of the “condition” is false, the statements between IF .. END IF
are ignored and the execution continues from the statement that follows END
IF.

Programming Fundamentals (Lecture Four) 7


One-Way Selection

The following figure shows the execution of this


selection statement.

Condition false

true
statements

continue

Programming Fundamentals (Lecture Four) 8


One-Way Selection .. Examples
◼Example 1:
Write an algorithm that takes an integer and prints its double
value if it is less than 50.
.50 ‫اكتب خوارزمية تأخذ عددًا صحي ًحا وتطبع قيمتها المضاعفة إذا كانت أقل من‬
First, we have to analyze the problem to understand what is its
requirements and how to solve it.
1- Analysis stage:
◼ Problem Input:
- An integer, say n
◼ Problem Output:
- The double value of n
◼ Criteria
if n < 50, print its double value
Programming Fundamentals (Lecture Four) 9
Example 1 .. cont.

2- Algorithm Design
ALGORITHM Double
INPUT n
IF ( n < 50 ) THEN
OUTPUT “The double value is “ , n * 2
END IF
OUTPUT “ Finished”
END

Programming Fundamentals (Lecture Four) 10


Example 1 .. cont.

3- Testing the algorithm


n (n < 50)
12 ---
true
The output:
The double value is 24
Finished

Programming Fundamentals (Lecture Four) 11


Example 1: C++ Program

#include <iostream>
using namespace std;
void main ( )
{
int n ;
cin >> n ;
if (n < 50)
cout << “The double value is “ << n * 2 << endl ;
cout << “ Finished “ << endl;
}

Programming Fundamentals (Lecture Four) 12


Example 2
Write an algorithm that takes two integers and prints the smallest
number. Use only one output statement.
.‫ استخدم عبارة إخراج واحدة فقط‬.‫اكتب خوارزمية تأخذ عددين صحيحين وتطبع أصغر عدد‬

1- Analysis stage:
◼ Problem Input:
- Two integers, say num1 and num2
◼ Problem Output:
- The smaller number
◼Criteria ‫المعايير‬
Print the smaller number using only one output statement

Programming Fundamentals (Lecture Four) 13


Example 2 .. cont.
2- Algorithm Design
ALGORITHM Smallest
INPUT num1, num2
temp  num1
IF ( num2 < num1 ) THEN
temp  num2
END IF
OUTPUT “The smallest number is “ , temp
END Smallest

Programming Fundamentals (Lecture Four) 14


Example 2 .. cont.
3- Testing the algorithm

num1 num2 temp (num2<num1)


9 3 ---
9
true
3
The output:
The smallest number is 3

Programming Fundamentals (Lecture Four) 15


Example 2: C++ Program
#include <iostream>
using namespace std;
void main ( )
{
int num1, num2, temp;
cin >> num1>>num2;
temp = num1;
if (num2 < num1)
temp = num2;
cout << “The smallest number is: “<< temp;
}

Programming Fundamentals (Lecture Four) 16


Example 3
Write an algorithm that takes three integers and prints their average,
if there summation is over 50.

.50 ‫ إذا كان المجموع أكبر من‬، ‫اكتب خوارزمية تأخذ ثالثة أعداد صحيحة وتطبع متوسطها‬
1- Analysis stage:
◼ Problem Input:
- Three integers, say n1, n2, n3
◼ Problem Output:
- The average of the three numbers, or nothing
◼Criteria
Calculate the average only if the summation of the numbers is over 50.

Programming Fundamentals (Lecture Four) 17


Example 3.. cont.
2- Algorithm Design
ALGORITHM Average
INPUT n1, n2, n3
sum  n1 + n2 + n3
IF ( sum > 50 ) THEN
avg  sum / 3
OUTPUT “The average is: “, avg
END IF
END Average

Programming Fundamentals (Lecture Four) 18


Example 3.. cont.
3- Testing the algorithm

n1 n2 n3 sum (sum>50) avg


60 70 80
210
true
70
The output:
The average is: 70

Programming Fundamentals (Lecture Four) 19


Example 3: C++ Program
#include <iostream>
using namespace std;
void main ( )
{
int n1, n2, n3, sum;
float avg;
cin >> n1>>n2>>n3;
sum = n1 + n2 + n3;
if (sum > 50)
{
avg = sum / 3.0;
cout << “The average is: “<< avg;
}
}
Programming Fundamentals (Lecture Four) 20
Two-Way Selection
This statement chooses- statements to run- from two sets of choices.
.‫ من مجموعتين من الخيارات‬- ‫ عبارات للتشغيل‬- ‫يختار هذا البيان‬
Syntax:

In pseudo code In C++

IF (condition) THEN if (logical expression)


statements1 statements1;
ELSE
else
statements2
END IF statements2;

Programming Fundamentals (Lecture Four) 21


Two-Way Selection .. cont.
◼ The semantics (execution) of this statement:
- If the value of the “condition” is true, the statements
after THEN are executed and the execution continues
to the statement after END IF.
- If the value of the “condition” is false, the statements
after ELSE are executed and the execution continues
from the statement that follows END IF.

- The following figure shows this execution:

Programming Fundamentals (Lecture Four) 22


Two-Way Selection .. cont.

false true
condition

statements2 statements1

continue

Programming Fundamentals (Lecture Four) 23


Two-Way Selection .. Examples
◼ Example 4:
Write an algorithm that takes two integers and prints the
smallest number with appropriate message.
.‫اكتب خوارزمية تأخذ عددين صحيحين وتطبع أصغر رقم برسالة مناسبة‬

1- Analysis stage:
◼ Problem Input:
- Two integers, say num1 and num2

◼ Problem Output:
- The smaller number

Programming Fundamentals (Lecture Four) 24


Example 4 .. cont.
2- Algorithm Design
ALGORITHM Smaller
INPUT num1, num2
IF ( num1 < num2 ) THEN
OUTPUT “The smaller number is “ , num1
ELSE
OUTPUT “The smaller number is “ , num2
END IF
END Smaller

Programming Fundamentals (Lecture Four) 25


Example 4 .. cont.

3- Testing the algorithm

num1 num2 (num2<num1)


9 3 ---
true
The output:
The smaller number is 3

Programming Fundamentals (Lecture Four) 26


Example 4: C++ Program

#include <iostream>
using namespace std;
void main ( )
{ int num1, num2 ;
cin >> num1 >> num2 ;
if ( num1 < num2 )
cout << “The smaller value is “ << num1 << endl ;
else
cout << “The smaller value is “ << num12 << endl ;
}

Programming Fundamentals (Lecture Four) 27


Example 5
Write an algorithm that takes prices of two items, if there total is over 100
JDs, calculate a discount of 40% and tax of 16%. Otherwise, calculate a
discount of 20% and tax of 6%. Then calculate the total price as: Total +
tax – Discount.
.٪16 ‫ وضريبة بنسبة‬٪40 ‫ احسب خص ًما بنسبة‬، ‫ دينار‬100 ‫ إذا كان المجموع أكثر من‬، ‫اكتب خوارزمية تأخذ أسعار صنفين‬
+ ‫ اإلجمالي‬:‫ ثم احسب السعر اإلجمالي على النحو التالي‬.٪6 ‫ وضريبة بنسبة‬٪20 ‫ احسب خص ًما بنسبة‬، ‫خالف ذلك‬
.‫ الخصم‬- ‫الضريبة‬
1- Analysis stage:
◼ Problem Input:
- Two prices, p1 and p2

◼ Problem Output:
- The total price of the two items
◼ Criteria
check whither the total prices is over 100 or not.

Programming Fundamentals (Lecture Four) 28


Example 5 .. cont.
2- Algorithm Design
ALGORITHM Total_Price
INPUT p1, p2
sub_total  p1 + p2
IF (sub_total > 100) THEN
Discount  sub_total * 0.4
Tax  sub_total * 0.16
ELSE
Discount  sub_total * 0.2
Tax  sub_total * 0.06
END IF
Total  sub_total + Tax - Discount
END Total_Price

Programming Fundamentals (Lecture Four) 29


Example 5: C++ Program
#include <iostream>
using namespace std;
void main ( )
{ float p1, p2, sub_total, discount, tax, total;
cin >> p1 >> p2;
sub_total = p1 + p2;
if ( sub_total > 100)
{
discount = sub_total * 0.4;
tax = sub_total * 0.16;
}
else
{
discount = sub_total * 0.2;
tax = sub_total * 0.06;
}
}
Programming Fundamentals (Lecture Four) 30
Multi Way Selection

◼ You can choose statement(s) to run from


many sets of choices.
.‫يمكنك اختيار العبارة (العبارات) لتشغيلها من عدة مجموعات من االختيارات‬
◼ There are two cases for this:
:‫هناك حالتان لهذا‬
(a) Multi way selection by nested IF structure
(b) Multi way selection by SWITCH structure

Programming Fundamentals (Lecture Four) 31


Multi Way Selection by Nested IF Structure

◼ The structure that contains another structure


of the same type is called a nested structure.
.‫تسمى البنية التي تحتوي على بنية أخرى من نفس النوع بالبنية المتداخلة‬
◼ In the Nested IF structure, the statements
that exists between IF and ELSE or between
IF and END IF can contain IF statement.
‫ و‬IF ‫ يمكن أن تحتوي العبارات الموجودة بين‬، ‫ المتداخلة‬IF ‫في بنية‬
IF. ‫على عبارة‬END IF ‫ و‬IF ‫ أو بين‬ELSE

Programming Fundamentals (Lecture Four) 32


Multi Way Selection by Nested IF Structure
◼ Syntax of one possible structure:
IF (condition1) THEN
Statements1
ELSE IF (condition2) THEN
Statements2
ELSE IF (Condition3) THEN
Statements3
ELSE IF (Condition4) THEN
Statements4
END IF
END IF
END IF
Note: The nest can be to many levels.
The following figure shows the execution of this structure.
.‫ يوضح الشكل التالي تنفيذ هذا الهيكل‬.‫ يمكن أن يكون التداخل على عدة مستويات‬:‫مالحظة‬

Programming Fundamentals (Lecture Four) 33


Multi Way Selection by Nested IF Structure
Syntax:
In pseudo code In C++
IF (condition1) THEN if (condition1)
Statements1 Statements1;
ELSE IF (condition2) THEN else if (condition2)
Statements2 Statements2 ;
ELSE IF (Condition3) THEN else if(Condition3)
Statements3 Statements3;
ELSE IF (Condition4) else if(Condition4)
THEN Statements4;
Statements4
END IF
END IF
END IF

Note: The nest can be to many levels.

Programming Fundamentals (Lecture Four) 34


Multi Way Selection by Nested If Structure .. Cont.

True
Condition1 Statements1

False

True
Condition2 Statements2
Rest of
False algorithm
True
Condition3 Statements3

False
Statements4

Programming Fundamentals (Lecture Four) 35


Multi Way Selection by Nested If Structure .. Examples

◼ Example 4:
Write an algorithm that inputs a student mark and outputs the
corresponding grade, where grades are as follows:
:‫ حيث تكون الدرجات كما يلي‬، ‫اكتب خوارزمية تُدخل عالمة الطالب وتخرج التقدير المقابل‬
mark grade
90-100 A
80-89 B
70-79 C
60-69 D
< 60 E

Programming Fundamentals (Lecture Four) 36


Example 4 .. Cont.
1- Analysis stage:
◼ Problem Input:
- student’s mark, mark

◼ Problem Output:
- grade

◼ Criteria
- according to the previous grade table

Programming Fundamentals (Lecture Four) 37


Example 4 .. Cont.
2- Algorithm Design
ALGORITHM Grades
INPUT mark
IF ( mark < 0 OR mark > 100 ) THEN
OUTPUT “ Mark out of range”
ELSE IF ( mark  90 AND mark  100 ) THEN
OUTPUT “A”
ELSE IF ( mark  80 ) THEN
OUTPUT “B”
ELSE IF ( mark  70 ) THEN
OUTPUT “C”
ELSE IF ( mark  60 ) THEN
OUTPUT “D”
ELSE OUTPUT “E”
END IF
END IF
END IF
END IF
END IF
END Grades
Programming Fundamentals (Lecture Four) 38
Example 4: C++ Program
#include <iostream>
using namespace std;
void main ( )
{ int mark ;
cin >> mark;
if ( mark < 0 || mark > 100 )
cout << “ Mark out of range” << endl;
else if ( mark >= 90 )
cout << “A” << endl ;
else if ( mark >= 80 )
cout << “A” << endl ;
else if ( mark >= 70 )
cout << “C” << endl ;
else if ( mark >= 60 )
cout << “D” << endl ;
else cout << “E” << endl ;
}

Programming Fundamentals (Lecture Four) 39


Comparison of Nested IF Structure and a Sequence of IF Structures
◼ Some times the nested IF structure is a good solution for a
given problem than a sequence of IF structures.
IF. ‫المتداخلة حالً جيدًا لمشكلة معينة بدالً من تسلسل هياكل‬IF ‫ تكون بنية‬، ‫في بعض األحيان‬
◼ Consider the following example:
(a) Nested case:
IF ( x > 0 ) THEN
pos_count  pos_count + 1
ELSE IF ( x < 0 ) THEN
neg_count  neg_count + 1
ELSE
zero_count  zero_count + 1
END IF
END IF

Programming Fundamentals (Lecture Four) 40


Comparison of Nested IF Structure and a Sequence of IF Structures

(b) Sequence case:


IF ( x > 0 ) THEN
pos_count  pos_count + 1
END IF
IF ( x < 0 ) THEN
neg_count  neg_count + 1
END IF
IF ( x = 0 ) THEN
zero_count  zero_count + 1
END IF

Programming Fundamentals (Lecture Four) 41


Comparison of Nested IF Structure and a Sequence of IF Structures

◼ In the previous example, only one statement should be


executed for any value of x.
x. ‫ يجب تنفيذ جملة واحدة فقط ألي قيمة لـ‬، ‫في المثال السابق‬
◼ In the sequence case, the sequence does not show
clearly that exactly one of the three statements is
executed for any value of x.
‫ ال يُظهر التسلسل بوضوح أن واحدة من العبارات الثالثة يتم‬، ‫في حالة التسلسل‬
x. ‫تنفيذها ألي قيمة من قيم‬
◼ In the nested case, only one statement is executed
exactly. Therefore, it is better than the sequence case.
‫ لذلك فهي أفضل من حالة‬.‫ يتم تنفيذ جملة واحدة فقط بالضبط‬، ‫في الحالة المتداخلة‬
.‫التسلسل‬

Programming Fundamentals (Lecture Four) 42


Problem : Read three numbers to print
the smallest one.
#include <iostream.h>
void main() {
int a, b, c;
cout<<"\nPlease Enter three numbers:";
cin>>a>>b>>c;
cout<<"\nMin= ";
if ((a < b) && (a < c))
cout<<a;
if ((b < a) && (b < c))
cout<<b;
if ((c < a) && (c < b))
cout<<c;
cout<<endl;
}

Programming Fundamentals (Lecture Four) 43


Program2 (nested if)
Sorting via comparisons
a<b?

b<c? c<b?

abc a<c? cba c<a?

acb cab bca bac

Programming Fundamentals (Lecture Four) 44


Program2 (nested if)
#include <iostream.h>
void main() {
int a, b, c;
cout<<"\nPlease Enter three numbers:";
cin>>a>>b>>c;
cout<<"\nMin= ";
if (a < b)
if (a < c)
cout<<a;
else
cout<<c;
else
if (b < c)
cout<<b;
else
cout<<c;
cout<<endl;
}
Programming Fundamentals (Lecture Four) 45
In Line Condition:

◼ You can include an in-line condition within a cout


command or in an assignment statement.
.‫ أو في بيان اإلسناد‬cout ‫يمكنك تضمين شرط في السطر داخل أمر‬
◼ Example1:
cout << (x>100? “Large” : ”Small”)
This is the same as the if condition:
if (x>100)
cout <<“Large”;
else
cout << “Small”
Programming Fundamentals (Lecture Four) 46
In Line Condition:
◼ Example2:
int x, y;
cin >> y;
x = (y<0 ? -1:1);

This is the same as the if condition:


if (y<0)
x = -1;
else
x = 1;

Note here, that the result of the in-line condition, should match the data
type of the variable at the left-hand side of the assignment statement

Programming Fundamentals (Lecture Four) 47


In Line Condition:
Note:
◼ In the previous examples, we used logical or relational
expressions as conditions for if statement, since they
generate a result of Boolean data types.
‫نظرا‬
ً ،if ‫ استخدمنا التعبيرات المنطقية أو العالئقية كشرط لبيان‬، ‫في األمثلة السابقة‬
.‫ألنها تولد نتيجة ألنواع البيانات المنطقية‬
◼ In some cases, you may need to use a variable as the
condition of an if statement. But, how this variable will be
interpreted into the result of the condition?
‫ولكن كيف سيتم‬if. ‫ قد تحتاج إلى استخدام متغير كشرط لتعليمة‬، ‫في بعض الحاالت‬
‫تفسير هذا المتغير في نتيجة الشرط؟‬
We can use: If(x)

Programming Fundamentals (Lecture Four) 48


In Line Condition:
◼ Example:
{
int x;
cin>> x;
if (x)
cout << “x is any number but zero”;
else
cout << “ x is zero”;
}
Notes: - a value of 0, is considered false in this case, while all other values,
either positive or negative, are considered true.
- The same applies for float variables.
- Character variables always return true.
.‫ صحيح‬،‫ إما إيجابية أو سلبية‬،‫ في حين تعتبر جميع القيم األخرى‬،‫ كاذبة في هذه الحالة‬0 ‫ يعتبر قيمة‬- :‫مالحظات‬
.‫األمر نفسه ينطبق على المتغيرات الفلوت‬
.‫متغيرات الحرف ترجع دائما صحيحة‬
Programming Fundamentals (Lecture Four) 49
In Line Condition:
Note:
▪ cin is used within the if condition, to check wither the user enters a
number or a character. If the user enters a number, it will be
considered true, and print the first output message. While if the user
enters character, it will be considered false, and print the second
output message.
، ‫ إذا أدخل المستخدم رق ًما‬.‫ للتحقق من إدخال المستخدم رق ًما أو حرفًا‬،if ‫ ضمن شرط‬cin ‫يتم استخدام‬
‫ فسيتم‬، ‫ بينما إذا قام المستخدم بإدخال الحرف‬.‫ وسيطبع أول رسالة إخراج‬، ‫فسيتم اعتباره صحي ًحا‬
.‫ وسيطبع رسالة اإلخراج الثانية‬، ‫اعتباره خطأ‬
▪ The same applies with the float variables.
▪ This technique is used to make sure the user enters a number in such
variables, and forbid him/her from entering characters instead.
.‫األمر نفسه ينطبق على المتغيرات الفلوت‬
.‫ ومنعه من إدخال األحرف بدالً من ذلك‬، ‫تستخدم هذه التقنية للتأكد من قيام المستخدم بإدخال رقم في هذه المتغيرات‬

Programming Fundamentals (Lecture Four) 50


In Line Condition:
Example:
Check this example:
void main ()
{
int x;
if (cin >> x)
cout << "number";
else
cout << "character";
}
Programming Fundamentals (Lecture Four) 51
Switch Statement in C++
◼ Syntax
switch (selector)
{ case L1: statements1; break;
case L2: statements2; break;

default: statements_n;
}
◼ Semantics:
This statement has the same meaning as in the
algorithmic language.
Programming Fundamentals (Lecture Four) 52
Example 1: C++ Program
#include <iostream>
using namespace std;
void main ( )
{
int lab;
cin >> lab;
switch ( lab )
{
case 503 : cout << “ C++ “ << endl; break;
case 508: cout << “ C# “ << endl; break;
case 512 : cout << “ Oracle “ << endl; break;
case 514: cout << “ PHP “ << endl; break;
case 507: cout << “ Java “ << endl; break;
default : cout << “ MS Office “ << endl;
}
}
Programming Fundamentals (Lecture Four) 53
Example 2: C++ Program
#include <iostream>
using namespace std;
void main ( )
{ char ch ;
cin >> ch ;
switch ( ch )
{ case ‘c’ : cout << “ do “ << endl; break;
case ‘d’ : cout << “ re “ << endl; break;
case ‘e’ : cout << “ mi “ << endl; break;
case ‘f’ : cout << “ f “ << endl; break;
case ‘g’ : cout << “ sol “ << endl; break;
case ‘a’ : cout << “ la “ << endl; break;
case ‘b’ : cout << “ ti “ << endl; break;
default : cout << “ Invalid note was read “ << endl;
}
Programming Fundamentals (Lecture Four) 54
Example 3: C++ Program
#include <iostream>
using namespace std;
void main ( )
{ char ch ;
cout << “ \n Enter the grade of student: “<<endl ;
cin >> ch;
switch (ch) {
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”; }
}
Programming Fundamentals (Lecture Four) 55
Flow Chart of switch statement

switch (grade)

case ‘A’ : case ‘a’ :

Display
“Excellent”

case ‘B’ : case ‘b’ :

Display
“Good”

Default :

“……..”

Programming Fundamentals (Lecture Four) 56


Example 4: C++ Program
#include <iostream>
using namespace std;
void main()
{ int x,y;
cout << "Enter 2 integer number: ";
cin >> x>>y;
switch (x+y)
{ case 7: cout << "Too small, sorry!";
break;
case 5: cout << "Good job!\n";
break;
case 4: cout << "Nice Pick!\n";
case 3: cout << "Excellent!\n";
break;
case 2: cout << "Masterful!\n";
break;
case 1: cout << "Incredible!\n";
break;
default: cout << "Too large!\n";
}
cout << "\n\n";
}

Programming Fundamentals (Lecture Four) 57


Example 5: C++ Program
#include <iostream>
using namespace std;
void main ( )
{ char ch ; float radius, area, circum;
cout << “ Enter the radius of a circle: “ ;
cin >> radius;
cout << “ Enter a to calculate the area of a circle or c to calculate its circumference:”
cin >> ch ;
switch (ch)
{ 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;
}
}

Programming Fundamentals (Lecture Four) 58


Convert Switch into IF
◼ Rewrite Example 3, using IF instead of Switch:
#include <iostream>
using namespace std;
void main ( )
{ char ch ;
cout << “ \n Enter the grade of student: “<<endl ;
cin >> ch;
if (ch == ‘A’ || ch == ‘a’)
cout<<”Excellent”;
else
if (ch == ‘B’ || ch == ‘b’)
cout<<”Good”;
else
if (ch == ‘C’ || ch == ‘c’)
cout<<”O.K”;
else
if (ch == ‘D’ || ch == ‘d’ || ch == ‘F’ || ch == ‘f’)
cout<<”poor”;
else
cout<<”invalid letter grade”; }
Programming Fundamentals (Lecture Four) 59
Convert IF into Switch – Example 6
#include <iostream> #include <iostream>
using namespace std; using namespace std;
void main ( )
void main ( )
{ char degree;
{ char degree; cout << “ \n Enter the temperature degree “<<endl ;
cout << “ \n Enter the temperature cin >> degree;
degree “<<endl ; switch (degree >= 50)
cin >> degree; {
case true: cout<<”Very Hot”; break;
if (degree >= 50) case false:
cout<<”Very Hot”; switch (degree >= 35 && degree <50)
else if (degree >= 35 && degree {
<50) case true: cout<<”Hot”; break;
case false:
cout<<”Hot”; switch (degree >= 20 && degree <35)
else if (degree >= 20 && degree {
<35) case true: cout<<”Fair”; break;
cout<<”Fair”; case false:
else if (degree >= 0 && switch (degree >= 0 && degree <20)
degree <20) {
case true: cout<<”Cold”; break;
cout<<”Cold”; case false: cout<<”Very Cold”;
else }
cout<<”Very Cold”; }
} } }

}
Programming Fundamentals (Lecture Four) 60
The End

Programming Fundamentals (Lecture Four) 61

You might also like