SlideShare una empresa de Scribd logo
1 de 27
Descargar para leer sin conexión
Chapter 5
CONTROL STRUCTURES I
(Selection)
BTE2313 Computer Programming
Lecturer: Samson Mekbib
LEARNING OUTCOME
Understanding basic problem solving
techniques.
To be able to develop algorithms through
the process of top – down, stepwise
refinement.
To be able to use if, if/else and switch
selection structures to choose among
alternative actions.
ALGORITHM and PSEUDOCODE
Algorithm: A procedure for solving a problem in terms of the
actions to be executed and the order in which these actions are
to be executed (recipe).
Pseudocode: an artificial and informal language that helps
programmer develop algorithms that will latter be converted to
structured C++ program.
A pseudocode is similar to everyday English: convenient and
user friendly although not actual computer programming
language.
A pseudocode consists of executable statements (those that are
executed when the program has been converted from
pseudocode to C++.
Examples of PSEUDOCODE
1. if (score is greater than or equal to 90)
grade is A
2. if (hours worked are less than or equal to 40)
wages = rate * hours
Otherwise
wages = (rate * 40) + 1.5 * (rate * (hours -40))
3. if (temperature is greater than 20 degrees and it is not raining)
go to play golf!
Equivalent C++ code:
1. if (score >= 90)
cout << “Grade: “ << ‘A’ << endl;
2. if (Hours <= 40)
wages = rate * Hours;
else if (Hours > 40)
wages = (rate*40) + 1.5 * (rate * (Hours -40));
3. if ((temp > 20) && (!(raining))
cout << “go out to play golf! “;
Flowchart
Flowchart: A graphical representation of an algorithm
Drawn using certain special – purpose symbols such
as rectangles, diamonds, ovals and small circles.
These symbols are connected by arrows called flow-
lines
Basic Shapes used in Flowchart
Example of flowchart:
The Basic If Statement
Syntax
if (Expression)
Action
If the Expression is true then
execute Action
Action is either a single
statement or a group of
statements within braces
Expression
Action
true false
Control Structures
A computer can process a program in one of the following
ways:
a) simple sequence – starts at the beginning and follows and
executes the statements in order. The simple input/output
examples we saw so far are simple sequence operation
*** However, C++ offers the use of the following control
structures for selection (decision making) and repetition:
b) selection – the program executes particular statements
depending on some conditions
c) repetition – the program repeats particular statements a
certain number of times based on some conditions
(discussed in detail in chapter 6)
Flow of execution:
sequence, selection & repetition
Conditional Constructs
Provide
 Ability to control whether a statement list is executed
Two constructs
 If statement
 if
 if-else
 if-else-if
 Switch statement
 Reading assignment : You will be required to present to the class
the concept of the switch control structure and demonstrate your
understanding using a C++ program example. Presentation will
be done in a group of 4-5 students. Presentation day will be the
first laboratory class after your semester break.
Example of if statement
 What will be the output when the following
statements run?
int m = 5;
int n = 10;
if (m < n)
++m;
++n;
cout << " m = " << m << " n = " n << endl;
Example: Absolute value of a number
if (Value < 0) {
Value = -Value;
}
Value < 0
Value = -Value
true f alse
Is our number negative?
If Value is not less
than zero then our
number is fine as is
If Value is less than
zero then we need to
update its value to
that of its additive
inverse
Our number is
now definitely
nonnegative
Sorting Two Numbers
cout << "Enter two integers: ";
int Value1;
int Value2;
cin >> Value1 >> Value2;
if (Value1 > Value2) {
int RememberValue1 = Value1;
Value1 = Value2;
Value2 = RememberValue1;
}
cout << "The input in sorted order: "
<< Value1 << " " << Value2 << endl;
Semantics
value2 < value1
int rememberValue1 = value1
value1 = value2
value2 = rememberValue1
true f alse
Are the numbers
out of order
Rearrange value1
and value2 to
put their values
in the proper
order
The numbers were
initially in order
The numbers were
rearranged into the
proper order
The numbers are in
order
The If-Else Statement
Syntax
if (Expression)
Action1
else
Action2
If Expression is true then execute
Action1 otherwise execute Action2
if (v == 0) {
cout << "v is 0";
}
else {
cout << "v is not 0";
}
Expression
Action1 Action2
true false
Example: Finding the Max
cout << "Enter two integers: ";
int Value1;
int Value2;
cin >> Value1 >> Value2;
int Max;
if (Value1 < Value2) {
Max = Value2;
}
else {
Max = Value1;
}
cout << "Maximum of inputs is: " << Max << endl;
Finding the Max
Value1 < Value2
Max = Value2 Max = Value1
true f alse
Is Value2 larger than Value1
Yes, it is . So Value2 is
larger than Value1. In
this case, Max is set
to Value2
No, its not. So Value
is at least as large as
Value2. In this case
Max is set to Value1
Either case, Max is set
correctly
if-else-if Statement
if ( nbr < 0 )
{
cout << nbr << " is negative" << endl;
}
else if ( nbr > 0 )
{
cout << nbr << " is positive" << endl;
}
else
{
cout << nbr << " is zero" << endl;
}
Nested if-else-if
 Example:
Switch structure
Switch structure
Switch structure
Example of a Switch structure
Practice by converting the above switch … case statements to if else
statements.
Exercise
Write a C++ program, which will input the marks for quiz, test and final
examination. Assume the full mark for each one is 100. Calculate the
final mark that the student receive using the following formula:
Final mark = 0.6 * final examination + 0.2* (test + quiz).
Calculate the grade that the student obtains based on the following table.
Display the mark, grade and the appropriate message to the student.
Mark Grade Message
0-49
50-64
65-74
75-100
F
C
B
A
You fail the course. Try again next semester.
You pass the course, but more exercises are needed.
You pass the course, Good luck in the next level.
Congratulations, you are excellent in this course.
Exercise
A sample output of your program should look like this

Más contenido relacionado

La actualidad más candente

Report Group 4 Constants and Variables
Report Group 4 Constants and VariablesReport Group 4 Constants and Variables
Report Group 4 Constants and VariablesGenard Briane Ancero
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++Neeru Mittal
 
Types of operators in C
Types of operators in CTypes of operators in C
Types of operators in CPrabhu Govind
 
Basic c operators
Basic c operatorsBasic c operators
Basic c operatorsdishti7
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c languagetanmaymodi4
 
Python Basic Operators
Python Basic OperatorsPython Basic Operators
Python Basic OperatorsSoba Arjun
 
Program design techniques
Program design techniquesProgram design techniques
Program design techniquesfika sweety
 
Best Techniques To Design Programs - Program Designing Techniques
Best Techniques To Design Programs - Program Designing TechniquesBest Techniques To Design Programs - Program Designing Techniques
Best Techniques To Design Programs - Program Designing TechniquesTech
 
C OPERATOR
C OPERATORC OPERATOR
C OPERATORrricky98
 
Operator in c programming
Operator in c programmingOperator in c programming
Operator in c programmingManoj Tyagi
 
Mesics lecture 4 c operators and experssions
Mesics lecture  4   c operators and experssionsMesics lecture  4   c operators and experssions
Mesics lecture 4 c operators and experssionseShikshak
 
Operators in c language
Operators in c languageOperators in c language
Operators in c languageAmit Singh
 
Flowchart pseudocode-examples
Flowchart pseudocode-examplesFlowchart pseudocode-examples
Flowchart pseudocode-examplesGautam Roy
 
pseudo code basics
pseudo code basicspseudo code basics
pseudo code basicsSabik T S
 

La actualidad más candente (19)

Report Group 4 Constants and Variables
Report Group 4 Constants and VariablesReport Group 4 Constants and Variables
Report Group 4 Constants and Variables
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++
 
Types of operators in C
Types of operators in CTypes of operators in C
Types of operators in C
 
Basic c operators
Basic c operatorsBasic c operators
Basic c operators
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
Python Basic Operators
Python Basic OperatorsPython Basic Operators
Python Basic Operators
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
 
Program design techniques
Program design techniquesProgram design techniques
Program design techniques
 
Best Techniques To Design Programs - Program Designing Techniques
Best Techniques To Design Programs - Program Designing TechniquesBest Techniques To Design Programs - Program Designing Techniques
Best Techniques To Design Programs - Program Designing Techniques
 
C OPERATOR
C OPERATORC OPERATOR
C OPERATOR
 
C operator and expression
C operator and expressionC operator and expression
C operator and expression
 
Operator in c programming
Operator in c programmingOperator in c programming
Operator in c programming
 
Mesics lecture 4 c operators and experssions
Mesics lecture  4   c operators and experssionsMesics lecture  4   c operators and experssions
Mesics lecture 4 c operators and experssions
 
Operator of C language
Operator of C languageOperator of C language
Operator of C language
 
Operators in c language
Operators in c languageOperators in c language
Operators in c language
 
Flowchart pseudocode-examples
Flowchart pseudocode-examplesFlowchart pseudocode-examples
Flowchart pseudocode-examples
 
Python : Operators
Python : OperatorsPython : Operators
Python : Operators
 
pseudo code basics
pseudo code basicspseudo code basics
pseudo code basics
 

Similar a Control Structures I Selection

Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_ifTAlha MAlik
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine LearningStudent
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)Prashant Sharma
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2yasir_cesc
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in Csana shaikh
 
03a control structures
03a   control structures03a   control structures
03a control structuresManzoor ALam
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
Lecture#3 Algorithms and computing
Lecture#3 Algorithms and computingLecture#3 Algorithms and computing
Lecture#3 Algorithms and computingNUST Stuff
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language CourseVivek chan
 
Lecture#2 Computer languages computer system and Programming EC-105
Lecture#2 Computer languages computer system and Programming EC-105Lecture#2 Computer languages computer system and Programming EC-105
Lecture#2 Computer languages computer system and Programming EC-105NUST Stuff
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.pptsanjay
 
Problem solving using computers - Chapter 1
Problem solving using computers - Chapter 1 Problem solving using computers - Chapter 1
Problem solving using computers - Chapter 1 To Sum It Up
 

Similar a Control Structures I Selection (20)

Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_if
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine Learning
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
03a control structures
03a   control structures03a   control structures
03a control structures
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Python Control structures
Python Control structuresPython Control structures
Python Control structures
 
Lecture#3 Algorithms and computing
Lecture#3 Algorithms and computingLecture#3 Algorithms and computing
Lecture#3 Algorithms and computing
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
 
Lecture#2 Computer languages computer system and Programming EC-105
Lecture#2 Computer languages computer system and Programming EC-105Lecture#2 Computer languages computer system and Programming EC-105
Lecture#2 Computer languages computer system and Programming EC-105
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
03b loops
03b   loops03b   loops
03b loops
 
Week 4
Week 4Week 4
Week 4
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.ppt
 
control structure
control structurecontrol structure
control structure
 
Problem solving using computers - Chapter 1
Problem solving using computers - Chapter 1 Problem solving using computers - Chapter 1
Problem solving using computers - Chapter 1
 
Daa unit 1
Daa unit 1Daa unit 1
Daa unit 1
 

Más de Widad Jamaluddin (9)

Chap 6 bte1013
Chap 6 bte1013Chap 6 bte1013
Chap 6 bte1013
 
Chap 8 bte1113
Chap 8 bte1113Chap 8 bte1113
Chap 8 bte1113
 
Chap 7 bte1013
Chap 7 bte1013Chap 7 bte1013
Chap 7 bte1013
 
Chap 5 bte1013
Chap 5 bte1013Chap 5 bte1013
Chap 5 bte1013
 
Chap 4 bte1013
Chap 4 bte1013Chap 4 bte1013
Chap 4 bte1013
 
Lab 07 voltage_current_divider
Lab 07 voltage_current_dividerLab 07 voltage_current_divider
Lab 07 voltage_current_divider
 
Chap 3 c++
Chap 3 c++Chap 3 c++
Chap 3 c++
 
Chap 2 c++
Chap 2 c++Chap 2 c++
Chap 2 c++
 
Chap 1 c++
Chap 1 c++Chap 1 c++
Chap 1 c++
 

Último

GBSN - Microbiology (Unit 2)
GBSN - Microbiology (Unit 2)GBSN - Microbiology (Unit 2)
GBSN - Microbiology (Unit 2)Areesha Ahmad
 
Biopesticide (2).pptx .This slides helps to know the different types of biop...
Biopesticide (2).pptx  .This slides helps to know the different types of biop...Biopesticide (2).pptx  .This slides helps to know the different types of biop...
Biopesticide (2).pptx .This slides helps to know the different types of biop...RohitNehra6
 
Animal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxAnimal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxUmerFayaz5
 
Natural Polymer Based Nanomaterials
Natural Polymer Based NanomaterialsNatural Polymer Based Nanomaterials
Natural Polymer Based NanomaterialsAArockiyaNisha
 
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...Sérgio Sacani
 
Green chemistry and Sustainable development.pptx
Green chemistry  and Sustainable development.pptxGreen chemistry  and Sustainable development.pptx
Green chemistry and Sustainable development.pptxRajatChauhan518211
 
GBSN - Biochemistry (Unit 1)
GBSN - Biochemistry (Unit 1)GBSN - Biochemistry (Unit 1)
GBSN - Biochemistry (Unit 1)Areesha Ahmad
 
Forensic Biology & Its biological significance.pdf
Forensic Biology & Its biological significance.pdfForensic Biology & Its biological significance.pdf
Forensic Biology & Its biological significance.pdfrohankumarsinghrore1
 
Biological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdfBiological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdfmuntazimhurra
 
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdfPests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdfPirithiRaju
 
Chemistry 4th semester series (krishna).pdf
Chemistry 4th semester series (krishna).pdfChemistry 4th semester series (krishna).pdf
Chemistry 4th semester series (krishna).pdfSumit Kumar yadav
 
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPirithiRaju
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRDelhi Call girls
 
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡anilsa9823
 
VIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C PVIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C PPRINCE C P
 
Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)PraveenaKalaiselvan1
 
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...anilsa9823
 
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.Nitya salvi
 

Último (20)

GBSN - Microbiology (Unit 2)
GBSN - Microbiology (Unit 2)GBSN - Microbiology (Unit 2)
GBSN - Microbiology (Unit 2)
 
Biopesticide (2).pptx .This slides helps to know the different types of biop...
Biopesticide (2).pptx  .This slides helps to know the different types of biop...Biopesticide (2).pptx  .This slides helps to know the different types of biop...
Biopesticide (2).pptx .This slides helps to know the different types of biop...
 
CELL -Structural and Functional unit of life.pdf
CELL -Structural and Functional unit of life.pdfCELL -Structural and Functional unit of life.pdf
CELL -Structural and Functional unit of life.pdf
 
Animal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxAnimal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptx
 
Natural Polymer Based Nanomaterials
Natural Polymer Based NanomaterialsNatural Polymer Based Nanomaterials
Natural Polymer Based Nanomaterials
 
The Philosophy of Science
The Philosophy of ScienceThe Philosophy of Science
The Philosophy of Science
 
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
 
Green chemistry and Sustainable development.pptx
Green chemistry  and Sustainable development.pptxGreen chemistry  and Sustainable development.pptx
Green chemistry and Sustainable development.pptx
 
GBSN - Biochemistry (Unit 1)
GBSN - Biochemistry (Unit 1)GBSN - Biochemistry (Unit 1)
GBSN - Biochemistry (Unit 1)
 
Forensic Biology & Its biological significance.pdf
Forensic Biology & Its biological significance.pdfForensic Biology & Its biological significance.pdf
Forensic Biology & Its biological significance.pdf
 
Biological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdfBiological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdf
 
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdfPests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
 
Chemistry 4th semester series (krishna).pdf
Chemistry 4th semester series (krishna).pdfChemistry 4th semester series (krishna).pdf
Chemistry 4th semester series (krishna).pdf
 
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
 
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡
 
VIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C PVIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C P
 
Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)
 
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
 
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
 

Control Structures I Selection

  • 1. Chapter 5 CONTROL STRUCTURES I (Selection) BTE2313 Computer Programming Lecturer: Samson Mekbib
  • 2. LEARNING OUTCOME Understanding basic problem solving techniques. To be able to develop algorithms through the process of top – down, stepwise refinement. To be able to use if, if/else and switch selection structures to choose among alternative actions.
  • 3. ALGORITHM and PSEUDOCODE Algorithm: A procedure for solving a problem in terms of the actions to be executed and the order in which these actions are to be executed (recipe). Pseudocode: an artificial and informal language that helps programmer develop algorithms that will latter be converted to structured C++ program. A pseudocode is similar to everyday English: convenient and user friendly although not actual computer programming language. A pseudocode consists of executable statements (those that are executed when the program has been converted from pseudocode to C++.
  • 4. Examples of PSEUDOCODE 1. if (score is greater than or equal to 90) grade is A 2. if (hours worked are less than or equal to 40) wages = rate * hours Otherwise wages = (rate * 40) + 1.5 * (rate * (hours -40)) 3. if (temperature is greater than 20 degrees and it is not raining) go to play golf! Equivalent C++ code: 1. if (score >= 90) cout << “Grade: “ << ‘A’ << endl; 2. if (Hours <= 40) wages = rate * Hours; else if (Hours > 40) wages = (rate*40) + 1.5 * (rate * (Hours -40)); 3. if ((temp > 20) && (!(raining)) cout << “go out to play golf! “;
  • 5. Flowchart Flowchart: A graphical representation of an algorithm Drawn using certain special – purpose symbols such as rectangles, diamonds, ovals and small circles. These symbols are connected by arrows called flow- lines
  • 6. Basic Shapes used in Flowchart
  • 7. Example of flowchart: The Basic If Statement Syntax if (Expression) Action If the Expression is true then execute Action Action is either a single statement or a group of statements within braces Expression Action true false
  • 8. Control Structures A computer can process a program in one of the following ways: a) simple sequence – starts at the beginning and follows and executes the statements in order. The simple input/output examples we saw so far are simple sequence operation *** However, C++ offers the use of the following control structures for selection (decision making) and repetition: b) selection – the program executes particular statements depending on some conditions c) repetition – the program repeats particular statements a certain number of times based on some conditions (discussed in detail in chapter 6)
  • 9. Flow of execution: sequence, selection & repetition
  • 10. Conditional Constructs Provide  Ability to control whether a statement list is executed Two constructs  If statement  if  if-else  if-else-if  Switch statement  Reading assignment : You will be required to present to the class the concept of the switch control structure and demonstrate your understanding using a C++ program example. Presentation will be done in a group of 4-5 students. Presentation day will be the first laboratory class after your semester break.
  • 11. Example of if statement  What will be the output when the following statements run? int m = 5; int n = 10; if (m < n) ++m; ++n; cout << " m = " << m << " n = " n << endl;
  • 12. Example: Absolute value of a number if (Value < 0) { Value = -Value; } Value < 0 Value = -Value true f alse Is our number negative? If Value is not less than zero then our number is fine as is If Value is less than zero then we need to update its value to that of its additive inverse Our number is now definitely nonnegative
  • 13.
  • 14. Sorting Two Numbers cout << "Enter two integers: "; int Value1; int Value2; cin >> Value1 >> Value2; if (Value1 > Value2) { int RememberValue1 = Value1; Value1 = Value2; Value2 = RememberValue1; } cout << "The input in sorted order: " << Value1 << " " << Value2 << endl;
  • 15. Semantics value2 < value1 int rememberValue1 = value1 value1 = value2 value2 = rememberValue1 true f alse Are the numbers out of order Rearrange value1 and value2 to put their values in the proper order The numbers were initially in order The numbers were rearranged into the proper order The numbers are in order
  • 16.
  • 17. The If-Else Statement Syntax if (Expression) Action1 else Action2 If Expression is true then execute Action1 otherwise execute Action2 if (v == 0) { cout << "v is 0"; } else { cout << "v is not 0"; } Expression Action1 Action2 true false
  • 18. Example: Finding the Max cout << "Enter two integers: "; int Value1; int Value2; cin >> Value1 >> Value2; int Max; if (Value1 < Value2) { Max = Value2; } else { Max = Value1; } cout << "Maximum of inputs is: " << Max << endl;
  • 19. Finding the Max Value1 < Value2 Max = Value2 Max = Value1 true f alse Is Value2 larger than Value1 Yes, it is . So Value2 is larger than Value1. In this case, Max is set to Value2 No, its not. So Value is at least as large as Value2. In this case Max is set to Value1 Either case, Max is set correctly
  • 20. if-else-if Statement if ( nbr < 0 ) { cout << nbr << " is negative" << endl; } else if ( nbr > 0 ) { cout << nbr << " is positive" << endl; } else { cout << nbr << " is zero" << endl; }
  • 25. Example of a Switch structure Practice by converting the above switch … case statements to if else statements.
  • 26. Exercise Write a C++ program, which will input the marks for quiz, test and final examination. Assume the full mark for each one is 100. Calculate the final mark that the student receive using the following formula: Final mark = 0.6 * final examination + 0.2* (test + quiz). Calculate the grade that the student obtains based on the following table. Display the mark, grade and the appropriate message to the student. Mark Grade Message 0-49 50-64 65-74 75-100 F C B A You fail the course. Try again next semester. You pass the course, but more exercises are needed. You pass the course, Good luck in the next level. Congratulations, you are excellent in this course.
  • 27. Exercise A sample output of your program should look like this