0% found this document useful (0 votes)
12 views31 pages

3 Selection

Uploaded by

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

3 Selection

Uploaded by

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

Selection Structures

School of Computing and Informatics


Computer Science Department
Prepared by Dr. Mohammad Yahia
Outlines
 Control Structures
 Conditions
Relational Operators
Logical Operators
 if statements
One-Alternative
Two-Alternatives
Nested If Statements
 switch Statement
Control Structures
 Control structures –control the flow of execution in a program or function.
 Three basic control structures:
 Sequential Flow - this is written as a group of statements bracketed by
{ and } where one statement follows another.
 Selection control structure - this chooses between multiple statements to
execute based on some condition.
 Repetition – this structure executes a block of code multiple times.

3
Compound Statements
 A Compound statement or a Code Block is written as a group of statements
bracketed by { and } and is used to specify sequential flow.
{
Statement_1;
Statement_2;
Statement_3;
}
 Example: the main function is surrounded by { }, and its statements are
executed sequentially.
 Function body also uses compound statements.

4
Conditions
 A program chooses among alternative statements by testing the values of
variables.
 0 means false
 Any non-zero integer means true, Usually, we’ll use 1 as true.

if (a>=b)
printf(“a is larger”);
else
printf(“b is larger”);

 Condition - an expression that establishes a criterion for either executing or


skipping a group of statements
 a>=b is a condition that determines which printf statement we execute.

5
Relational and Equality Operators
 Most conditions that we use to perform comparisons will have one of these forms:
 variable relational-operator variable: e.g. a < b
 variable relational-operator constant: e.g. a > 3
 variable equality-operator variable: e.g. a == b
 variable equality-operator constant: e.g. a != 10
Operator Meaning Type
< less than relational
> greater than relational
<= less than or equal to relational
>= greater than or equal to relational
== equal to equality
6
!= not equal to equality
Logical Operators
 logical expressions - expressions that use conditional statements and logical
operators.
 && (and)
 A && B is true if and only if both A and B are true
 || (or)
 A || B is true if either A or B are true
 ! (not)
 !(condition) is true if condition is false, and false if condition is true
 This is called the logical complement or negation
 Example
 (salary < 10000 || dependents > 5)
 (temperature > 90.0 && humidity > 90)
 !(temperature > 90.0)
7
Truth Table for (&&, ||, ! ) Operators
A B A && B A || B

False (zero) False (zero) False (zero) False (zero)

False (zero) True (non-zero) False (zero) True (1)

True (non-zero) False (zero) False (zero) True (1)

True (non-zero) True (non-zero) True (1) True (1)

A !A

False (zero) True (non-zero)

True (non-zero) False (zero)

8
Operator Precedence
 Operator’s precedence determine the
order of execution. Use parenthesis to ! + - & (unary
clarify the meaning of expression. operations)
 Relational operator has higher
precedence than the logical operators.
*, /, %
 Ex: followings are different. +, -
(x<y || x<z) && (x>0.0)
x<y || x<z && x>0.0 <, >, <=, >=
==, !=
&&
||
=
9
One-way selection (if-statement)

 Used to execute a statement or a compound_statement when a condition is true.


 What is a compound statement?

Simple Compound statement


statement
if(condition) if(condition)
statement1; compound_statement1
One-way selection (if-statement)

 Examples:

Simple statement Compound statement


if(condition) if(condition)
statement1; compound_statement1
Two-way selection (if-else statement)

 An if-else statement is used to execute a


statement or a compound-statement when a
condition is true; and another statement or
compound-statement when that condition is
false.

Simple statement Compound statement


if(condition) if(condition)
statement1; compound_statement1
else else
statement2; compound_statement2
Two-way selection (if-else statement)

 Examples:
Simple statement Compound statement
if(condition) if(condition)
statement1; compound_statement1
else else
statement2; compound_statement2
Multi-way selection with an else option
(if- else if – else)
 Used to execute the first statement or the first
compound_statement whose corresponding condition
is true. The statement in the else part is executed if
each condition is false.

Simple statement Compound statement


if(condition1) if(condition1)
statement1; compound_statement1
else if(condition2) else if(condition2)
statement2; compound_statement2
else if(condition3) else if(condition3)
statement3; compound_statement3
. .
. .
. .
else if(conditionM) else if(conditionM)
statementM; compound_statementM
else else
statementN; compound_StatementN
Multi-way selection with an else option
(if- else if - else)
 Example: The following
program prints the grade
and the letter grade based
on a grade entered by a
user. If the user enters an
invalid grade, the program
prints an Error message.
 Exercise: Write the program
using the logical operator
&& for all conditions such
as:
if (grade >= 85.0 && grade
< 100)
Multi-way selection without an else option
(if- else if – else if)
 Used to execute the first statement or the first
compound_statement whose corresponding condition is true.
The statement in the else part is executed if each condition is
false.
Simple Compound statement
statement
if(condition1) if(condition1)
statement1; compound_statement1
else else if(condition2)
if(condition2) compound_statement2
statement2; else if(condition3)
else compound_statement3
if(condition3) .
statement3; .
. .
. else if(conditionM)
. compound_statementM
else
if(conditionM)
statementM;
Multi-way selection without an else option
(if- else if – else if)
 Example: The following
program prints the grade
and the letter grade based
on a grade entered by a
user. If the user enters an
invalid grade, the program
prints an Error message.
 Exercise: Rewrite the
program where the first if
should be the following
statement:
if (grade >= 0 && grade <
60)
Nested if Statement
 The compound statement in an if-branch or an else-branch of an if-statement may
contain one or more of any type of if-statement discussed in the previous pages.
 Nested if structures can be complicated. So we prefer to use multi-way if structure
if(condition1){
statement1;
if(condition2)
statement2;
else
statement3;
statement4;
}
else{
if(condition3)
compound_statementA
else if(condition4)
compound_statementB
else
compound_StatementC
statementD
}
Nested if Statement
 Example of Nested if:

 Or we could use an equivalent statement that uses a single if with a compound


condition:
Using the curly braces { } – Yes/No?
 If there is only one statement between the { } braces, you can omit the braces.
 To be safe, you may want to always use curly bracket {, even if there is only a
single statement.
Without { } With { }

20
ASCII Table
 Characters are actually represented
in C as integer values.
 Each character is represented by its
ASCII code (e.g A = 65. B = 66, etc).
 The table after the program below
shows the printable ASCII characters
and their corresponding ASCII codes.

21
Character Comparison
 Printing a char variable
using “%c” will print the
character but printing it
with “%d” will print the
ASCII code.
 Similarly, printing an
integer variable with “%c”
will also print the character
provided the value is within
the range of character
values.

 C allows character
comparison using relational
and equality operators.
 During comparison, orders 22
based on ASCII table is
followed.
Example
 Given a person’s salary, we want to calculate the tax due by adding the base tax to the
product of the percentage times the excess salary over the minimum salary for that range.
Salary Range Base tax Percentag
e of Excess
0.00 – 14,999.99 0.00 15

15,000.00 – 2,250.00 18
29,999.99
30,000.00 – 5,400.00 22
49,999.99
50,000.00 – 11,000,00 27
79,999.99
80,000.00 – 21,600.00 33
150,000.00

23
Example (Divisible by 3 and 5)
 Write a C program that prompts and reads an integer number x. It then checks the number for
divisibility by 3 and 5 and prints one of the following messages accordingly:
 The number x is divisible by both 3 and 5
 The number x is divisible by 3 but not 5
 The number x is divisible by 5 but not 3
 The number x is neither divisible by 3 nor by 5

24
Example (Divisible by 3 and 5)
 More efficient method (why?)

25
Some Common Errors in if Statements
1. Using wrong conditions; The following condition is true for all values of x. The correct
condition is (x >= 0 && x <= 4)

2. Using assignment operator = instead of equals == operator in conditions.


The condition always evaluate to true The condition always evaluate to true

3. Not using a compound statement where it is necessary to do so


A syntax error: ‘else’ without a Must be written as
previous ‘if’

26
Some Common Errors in if Statements
4. Using conditions without surrounded parentheses ( )
No parentheses ( ) around the Parentheses ( ) surrounds the
condition condition

5. A semicolon after the condition. C will interpret this as there is nothing to do if the condition
is true.

27
Switch statements

 The switch statement is a better


way of writing a program when a
series of if-else if occurs.
 The switch statement selects one
of several alternatives.
 The switch statement is especially
useful when the selection is based
on the value of a single variable or
of a simple expression
 This is called the controlling
expression
 In C, the value of this expression
may be of type int or char, but
not of type double.

28
Switch statements

 The case constants must be distinct char or int constants; otherwise there is a
syntax error.
 The default label together with its statementList is an optional.
 The default label need not be the last label if it is followed by break statement.
 The break statement following a statementList is an optional. (What is the effect
of removing break?)
 The switch expression is evaluated and then the statementList of the case value
that equals to the expression is executed. If there is a break statement, control
passes to the statement after the switch; otherwise, the following statementLists
are executed until a break statement is encountered, control then passes to the
statement after the switch statement.
 If switch expression is not equal to any case value, the statementList for the
default label is executed, and if the default label is the last one or if its statement
list is followed by a break statement, control passes to the statement after the
switch statement.
29
 If switch expression is not equal to any case value and there is no default label,
control passes to the statement after the switch without executing any switch
Example of a switch Statement with char Case Labels
 Write a C program to choose the class of a ship
according to the first character in the word,
where classes as follows: (B or b for Battleship),
(C or c for Cruiser), (D or d for Destroyer), and
(F or f for Frigate)
 Suppose the user enter the letter ‘D’:
 This takes the value of the variable
classID, which is D, and compares it to
each of the cases in a top down
approach.
 It stops at the first case that is equal
to the value of the variable classID,
which is at line 16.
 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.
 Finally, the control passes to the 30
statement after the switch body.
 What will happen if the user enters the letter
Example of a switch Statement with int Case Labels
 Write a C program to display the
name of a digit; For example; if the
user enter 3, the program should
display three, if the user enters 8,
the program should display eight,
and so on. If the user enters any
other character rather than a digit,
the program should display an error
message.

31

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy