0% found this document useful (0 votes)
43 views43 pages

Lecture 6 - Fall 2023

Uploaded by

doaaayman784
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)
43 views43 pages

Lecture 6 - Fall 2023

Uploaded by

doaaayman784
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/ 43

CS111 | COM101 Intro.

to Computer Science
Computer Science Dept.
Helwan University

Lecture 6
Control Structures: Selection
the If .. Else & Switch .. Case
6.1 Control Structures & Single-Selection Statements (If .. Then)
 Control Structures – Sequence Control Structure – Selection Control
Structure (Decisions) – Types of Selection Statements – Single-
Selection Statements – If .. Then Statements
6.2 Double-Selection Statements (If .. Else) & the Conditional Operator
 Double-Selection Statements – If .. Else Statements – Compound
Faculty of
Statement (Block) – Conditional Operator ( ? : )
Computers &
6.3 Multiple Selection Statements (Nested if & Switch Case) Artificial Intelligence
 Multiple Selection / Cases Statements – Nested if Statements –
Switch–Case Statements FALL 2023
Where are we now .. ?!
0: Course Introduction & Plan
1: Computational Thinking – Part 1 (Computers, Computer Science, & Binary Representation)
2: Computational Thinking – Part 2 (Types of Hardware, Algorithms, & Programming
Languages)
3: Computational Thinking – Part 3 (Types of Software, Basics of Programs, & Compilation)
4: Variables, Constants, & Data Types in C
5: Arithmetic & Bitwise Operations, Logical & Relational Operators, and Precedence
6: Control Structures – Selection (Decisions)
7: Control Structures – Repetition (Loops)
8: C Built-In Functions & Solved Examples (1st Set)
9: User–Defined Functions & Scope of Variables
10: Number Systems, Binary Arithmetic, & the Complements Representation
11: Recursion, Function Overloading, & Call-by-Reference versus Call-by-Value
12: Solved Examples (2nd Set)

Course & Lectures are based on their counterparts in the following:


o Harvard University's CS50; An introduction to the intellectual enterprises of computer science and the art of
programming, Harvard School of Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++ (2011), and 6.S096 Introduction to C and
C++ (2013), MIT (Massachusetts Institute of Technology) OpenCourseWare.
Lecture 6: Control Structures: Selection
the If .. Else & Switch .. Case Statements
6.1 Control Structures & Single-Selection Statements (If .. Then)
 Control Structures & the Sequence Control Structure
 Selection Control Structure (Decisions) & the Types of Selection Statements
 Single-Selection Statements: the If .. Then Statements

6.2 Double-Selection Statements (If .. Else) & the Conditional Operator


 Double-Selection Statements: the If .. Else Statements
 Compound Statement (Block)
 The Conditional Operator ( ? : )

6.3 Multiple Selection Statements (Nested if & Switch Case)


 Multiple Selection Statements
 A Multiple Cases Example: the Nested if Statements
 Multiple Cases Statements: the Switch–Case Statements
Control Structures ..

Control
Structures

Selection Repetition
Sequence
(Decisions) (Loops)

Step-by-Step Choose a path Repeat a sequence


sequentially in from multiple of statements ..
order .. options ..
Example 6.1: Calculate the Power of two
numbers ..
Write a program that calculates the power of two numbers,
x and y. The program should prompt the user through a
message to input 2 numbers, then display “x to the power
of y”.

Pseudocode:

Step 1: Input 2 numbers x and y


Step 2: Power xy
Step 3: Print Power
5
Example 6.1: Calculate the Power of two
numbers .. Start
Flowchart:
Input two
numbers x and Y

Power ← xy

Output Power

End 6
Example 6.1: Calculate the Power of two
numbers ..
So, .. your program should behave like this:

7
Example 6.1: Calculate the Power of two
numbers ..

#include <stdio.h> // The header file including the printf & scanf
#include <math.h> // The header file including the pow function
int main() // The main function, execution starts here
{
float x, y; // Variables Declarations
// Prompt message to read the 2 numbers
printf( "Please enter 2 integers x & y to calculate the power x^y\n" );
scanf( "%f %f", &x, &y ); // Reads the 2 numbers
printf( "%f to the power of %f equals %f\n", x, y, pow(x, y) );
return 0; // Program ended successfully
}
8
Control Structures ..

Control
Structures

Selection Repetition
Sequence
(Decisions) (Loops)

Step-by-Step Choose a path Repeat a sequence


sequentially in from multiple of statements ..
order .. options ..
Selection (Decisions / Branching) ..

IF Condition THEN Statement(s) ELSE Statement(s)

YES Statement(s)
Condition
NO Statement(s)

NO YES
A < B?
Types of Selection Statements

o Single-Selection Statement:
o if statements, when the condition is:
o true performs an action;
o false the action is skipped.
o Double-Selection Statement:
o if .. else statements, when the condition is:
o true performs an action;
o false performs another action.
o Multiple-Selection Statement:
o Nested if .. else statements
o switch .. case statements
11
Types of Selection Statements ..
Single-Selection Statements ..
if (condition)
- a null statement, or
Statement(s); - a single statement, or
- a block of statements:
{
statement1;
statement2;…
}

true
condition
12

false
12
Example 6.2: Determine Passed Students
Write a program that reads a student’s grade and displays
“Passed” if his/her grade is greater than or equal to 60. The
program should prompt the user through a message to input
a grade, then displays Passed if that grade was greater than
or equal to 60.

Pseudocode:

Step 1: Input Grade


Step 2: If Grade >= 60
Step 3: Print “Passed”
13
Example 6.2: Determine Passed Students
Flowchart:

Start

Read Grade

Print Grade
“Passed” Yes >= 60
No
End

14
Example 6.2: Determine Passed Students

So, .. your program should behave like this:

15
Example 6.2: Determine Passed Students

#include <stdio.h> // The header file including the printf & scanf
int main() // The main function, execution starts here
{
int grade; // Variable Declaration
// Prompt message to read a grade
printf("Please enter a student's grade (from 0 to 100)\n");
scanf("%d", &grade); // Reads a grade
if (grade >= 60) // Decision (Selection) Indentation is a good
printf("Passed\n"); programming practice.
return 0; // Program ended successfully
}
16
Up Next ..
Exercises Section 6.2
What have we learned?
 Write down an algorithm using pseudocode,
represent it graphically using a flowchart, and
finally write the corresponding C program that:
1) Reads a positive integer N and determines
whether N is even or odd.
2) Reads two positive integers, determines which
has a greater value, and then prints this value
only if it is even.
 Write a C program that calculates the cube of an
integer number. The program should be
implemented by using two methods:
1) without using the “pow()” function, and ..
2) using the “pow()” function.
Lecture 6: Control Structures: Selection
the If .. Else & Switch .. Case Statements
6.1 Control Structures & Single-Selection Statements (If .. Then)
 Control Structures & the Sequence Control Structure
 Selection Control Structure (Decisions) & the Types of Selection Statements
 Single-Selection Statements: the If .. Then Statements

6.2 Double-Selection Statements (If .. Else) & the Conditional Operator


 Double-Selection Statements: the If .. Else Statements
 Compound Statement (Block)
 The Conditional Operator ( ? : )

6.3 Multiple Selection Statements (Nested if & Switch Case)


 Multiple Selection Statements
 A Multiple Cases Example: the Nested if Statements
 Multiple Cases Statements: the Switch–Case Statements
Types of Selection Statements ..
Double-Selection Statements ..
if .. else statement (in the following Syntax):
if (condition)
Indentation; (the space before
Statement(s)_A; statements A and B) is a good
else programming practice.
Statement(s)_B;
true false
condition

Note: if .. else are keywords; written in small letters .. 19


Example 6.3: Determine Final Grade
Write a program to determine a student’s final grade, and
then indicate whether he/she is passing or failing. The final
grade is calculated as the average of four marks. The
program should prompt the user through a message to input
the marks, then displays “Pass” if that average was greater
than or equal to 50, and “Fail” otherwise.

Pseudocode:
Step 1: Input a set of 4 marks (M1, M2, M3, & M4)
Step 2: Calculate their average by summing & dividing by 4
Step 3: If average is below 50
Step 4: Print “Fail”
Step 5: Else
Step 6: Print “Pass” 20
Example 6.3: Determine Final Grade
Flowchart:
START
Input M1, M2, M3, M4

GRADE  ( M1 + M2 + M3 + M4 ) / 4
is
GRADE < 50
No Yes
PRINT “PASS” PRINT “FAIL”

END 21
Example 6.3: Determine Final Grade

So, .. your program should behave like this:

22
Example 6.3: Determine Final Grade
#include <stdio.h> // The header file including the printf & scanf
int main() // The main function, execution starts here
{
// Variables Declaration
int mark_1, mark_2, mark_3, mark_4; float average;
// Prompt message to read the 4 marks
printf("Please enter the student’s 4 marks (each from 0 to 100)\n");
// Read the marks
scanf("%d %d %d %d", &mark_1, &mark_2, &mark_3, &mark_4);
average = (mark_1 + mark_2 + mark_3 + mark_4) / 4.0;
if (average < 50) // Decision (Selection)
printf("Fail\n");
else
printf("Pass\n");
return 0; // Program ended successfully
23
}
Compound Statement (Block) ..

if ( grade >= 60 ) {
printf("Passed.\n");
} // end if
else {
printf ("Failed.\n");
printf ("You must take this course again.\n");
} // end else

If the if’s/else's body has more than


one statement, curly braces should
enclose them. 24
Conditional Operator ( ? : )
.. .. ..
if ( grade >= 60)
{ printf( "Passed\n");}
// end if
else {
printf( "Failed\n" );
}// end else

≡ grade >= 60 ? printf("Passed") : printf("Failed ");


Condition Executed if true Executed if false

≡ printf( "%s\n", grade >= 60 ? "Passed" : "Failed");


Condition if true if false
25
Exercises
What have we learned?

 What is the output of the following program fragment?


length = 25;
width = 60;
if (length == 50)
height = 4;
else
height = 8;
printf ("%d %d %d", length, width, height);
Up Next ..
Additional Section 6.3
Resources
 C - if...else statement:
https://www.tutorialspoint.com/cprogramming/if_else_state
ment_in_c.htm
 Conditional or Ternary Operator (?:) in C/C++:
https://www.geeksforgeeks.org/conditional-or-ternary-
operator-in-c-c/
Lecture 6: Control Structures: Selection
the If .. Else & Switch .. Case Statements
6.1 Control Structures & Single-Selection Statements (If .. Then)
 Control Structures & the Sequence Control Structure
 Selection Control Structure (Decisions) & the Types of Selection Statements
 Single-Selection Statements: the If .. Then Statements

6.2 Double-Selection Statements (If .. Else) & the Conditional Operator


 Double-Selection Statements: the If .. Else Statements
 Compound Statement (Block)
 The Conditional Operator ( ? : )

6.3 Multiple Selection Statements (Nested if & Switch Case)


 Multiple Selection Statements
 A Multiple Cases Example: the Nested if Statements
 Multiple Cases Statements: the Switch–Case Statements
Example 6.4: A Multiple Cases Example
Nested if Statements ..
It tests for multiple cases by placing if .. else statement inside
other if .. else statements [called Nested if statements]:
Example:
Read a student’s grade from the user, & write the following:
A, for exam grades greater than or equal to 85,
B, for exam grades greater than or equal to 75,
C, for exam grades greater than or equal to 65,
D, for exam grades greater than or equal to 50,
F, for all other grades.
Example 6.4: A Multiple Cases Example
Nested if Statements ..
Start Flowchart
Read Grade

Yes Grade No
>=85
Print “A” Yes Grade No
>=75
Print “B” Yes Grade No
>=65
Print “C” Yes Grade No
>=50
Print “D” Print “F”

End
Example 6.4: A Multiple Cases Example
if ( grade >= 85 ) { Nested if Statements ..
printf("A.\n");
} // end if
else {
if ( grade >= 75 ) {
printf("B.\n");
} // end if
else {
if ( grade >= 65 ) { Only a single statement
printf("C.\n");
} // end if will be executed ..
else {
if ( grade >= 50) {
printf("D.\n");
} // end if
else { printf("F.\n");
} // end else
} // end else
} //end else
} // end else
Multiple Cases Statements ..
Switch – Case Statements ..

o Nested if .. else can be very hard to follow, and


sometimes may be confusing.

o Therefore, a switch .. case statement is used for


multiple selection.

Note: only used with integer and character constants ..


Multiple Cases Statements ..
Switch – Case Statements ..
switch (controlling expression)
{
case value1:
If break; is forgotten ..
statements 1;
break; The first matching case
case value2: that is true + all of the
statements 2; consecutive cases will
break; be executed.
...
Don’t forget the
case valueN:
statements N; break!
break;
default:
statements;
}
Multiple Cases Statements ..
Switch – Case Statements ..
Example 6.5: A Basic Menu
An example on Switch–Case Statements ..
Your program should read two integer numbers from the
user, then display a menu to the user with 2 options:
- If (s)he typed 1 the two integers will be added and their
sum will be displayed, and ..
- If (s)he typed 2 the two integers will be subtracted and the
result will also be displayed.
- If (s)he typed any other value, a message should be
displayed indicating that this is an illegal option.
Example 6.5: A Basic Menu
An example on Switch–Case Statements ..
You should first:
- Read the 2 Numbers num1 & num2. Flowchart
- Display the Menu Options.
- Read the Menu Option menuNo.

Yes menuNo No
== 1
result =
num1 + num2 Yes No
menuNo
== 2
result =
break; num1 - num2 display
illegal choice
break;

- Display the result.


Example 6.5: A Basic Menu
int num1, num2, menuNo, result;
printf ("Enter 2 integer numbers"); scanf ("%d %d", &num1, &num2);
printf ("Choose an operation (1 to ADD or 2 to SUBTRACT)");
scanf ("%d", &menuNo);
switch ( menuNo ) {
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
default:
printf ("illegal choice");
} /* end switch */
printf ("The result is %d", result);
Example 6.5: A Basic Menu
int num1, num2, menuNo, result;
printf ("Enter 2 integer numbers"); scanf ("%d %d", &num1, &num2);
printf ("Choose an operation (1 to ADD or 2 to SUBTRACT)");
scanf ("%d", &menuNo);
switch ( menuNo ) {
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
Is the program’s logic
default:
correct? What is wrong
printf ("illegal choice");
with this printf statement?
} /* end switch */
printf ("The result is %d", result);
Example 6.5: A Basic Menu
int num1, num2, menuNo, result;
printf ("Enter 2 integer numbers"); scanf ("%d %d", &num1, &num2);
printf ("Choose an operation (1 to ADD or 2 to SUBTRACT)");
scanf ("%d", &menuNo);
switch ( menuNo ) {
case 1:
result = num1 + num2;
printf ("The result is %d", result); break;
case 2:
result = num1 - num2;
printf ("The result is %d", result); break;
default:
printf ("illegal choice"); a Solution ..
} /* end switch */
Example 6.5: A Basic Menu
int num1, num2, menuNo, result;
printf ("Enter 2 integer numbers"); scanf ("%d %d", &num1, &num2);
printf ("Choose an operation (1 to ADD or 2 to SUBTRACT)");
scanf ("%d", &menuNo);
switch ( menuNo ) {
case 1:
result = num1 + num2; break;
case 2:
result = num1 - num2; break;
default:
printf ("illegal choice"); another Solution ..
} /* end switch */
if (( menuNo == 1) || (menuNo == 2))
printf ("The result is %d", result);
Example 6.5: A Basic Menu
int num1, num2, menuNo, result;
printf ("Enter 2 integer numbers"); scanf ("%d %d", &num1, &num2);
printf ("Choose an operation (1 to ADD or 2 to SUBTRACT)");
scanf ("%d", &menuNo);
switch ( menuNo ) {
case 1:
result = num1 + num2; break;
case 2:
result = num1 - num2; break;
} /* end switch */
( menuNo == 1 || menuNo == 2) ? printf ("The result is %d", result) :
printf ("illegal choice");

a third Solution ..
Exercises
What have we learned?

 Write down an algorithm using pseudocode, represent


it graphically using a flowchart, and finally write the
corresponding C program that calculates the net salary
for an employee in a company, given that:
1) If the salary is greater than 3000$, tax is 10%.
2) If the salary is greater than 5000$, tax is 15%.
3) If the salary is less than 3000$, tax is 5%.
4) If the salary is between 1000$ and 1500$,
additional 200$ are added.
Up Next ..
Additional Lecture 7
Resources
 C – If..else, Nested If..else and else..if Statement with example:
https://beginnersbook.com/2014/01/c-if-else-statement-example/

 C - switch statement:
https://www.tutorialspoint.com/cprogramming/switch_statement
_in_c.htm

Thank you!

You might also like