SlideShare a Scribd company logo
1 of 21
CONDITIONAL
STATEMENTS
NESTED IF STATEMENTS
NESTED IF
STATEMENTS
We can have two or more if statements inside each other to
check multiple conditions
 These are called nested if statements
Nested if statements can be used to test more than one
condition
Use indentation to reflect nesting and aid readability
 Typically indent 3-4 spaces or one tab
Need to take care when matching up { } brackets
 This way you can decipher the nesting of conditions
2
NESTED IF
STATEMENTS
if ( logical expression1 )
{
if ( logical expression2 )
{
// Statements to execute if expressions1 and expression2 are true
}
else
{
// Statements to execute if expression1 true and expression2 false
}
}
else
{
// Statements to execute if expression1 false
}
3
FLOWCHART FOR A
NESTED IF STATEMENT
4
NESTED IF CODE
// Determine loan qualification
if (employed == ‘y’)
{
if (recentGrad == ‘y’)
{
cout << “You qualify!”
}
}
Note: this could be done with one if and two conditions.
5
NESTED IF CODE
// Determine loan qualification using one if and
//two conditions
if (employed == ‘y’ && recentGrad == ‘y’)
{
cout << “You qualify!”
}
6
NESTED IF
STATEMENTS
// Simple nested if example
cin >> a >> b;
if (a < b)
{
cout << “A is smaller than Bn”;
if ((a > 0) && (b > 0))
cout << “A and B are both positiven”;
else
cout << “A or B or both are negativen”;
}
7
NESTED IF
STATEMENTS
// Ugly nested if example
if (a > 0) {
if (b < 0) {
a = 3 * b;
c = a + b; } }
else {
a = 2 * a;
c = b / a; }
 It is hard to see what condition the else code goes with
8
NESTED IF
STATEMENTS
// Pretty nested if example
if (a > 0)
{
if (b < 0)
{
a = 3 * b;
c = a + b;
}
}
else
{
a = 2 * a;
c = b / a;
}
9
BOOLEAN VARIABLES
 In C++ we can store true/false values in Boolean variables
 The constants “true” and “false” can be used to initialize
these variables
 bool Done = true;
 bool Quit = false;
 Boolean expressions can also be used to initialize these
variables
 bool Positive = (a >= 0);
 bool Negative = (b < 0);
10
BOOLEAN VARIABLES
 Boolean variables and true/false constants can also be
used in logical expressions
 (Done == true) is true
 (Quit != true) is true
 (Done == Quit) is false
 (true == Positive) is true
 ((a < b) == false) is false
 (Negative) is false
11
BOOLEAN VARIABLES
 Internally C++ stores Boolean variables as integers
 0 is normally used for false
 1 is normally used for true
 Any non-zero value is also considered true
 It is considered “bad programming style” to use integers
instead of true/false
 bool Good = 0;
 bool Bad = 1;
 bool Ugly = a;
12
BOOLEAN VARIABLES
 Integers are used when writing Boolean values
 cout << Good will print 0
 cout << Bad will print 1
 cout << Ugly will also print 1
 Integers are also used when reading Boolean values
 cin >> Good;
 Entering 0 sets Good variable to false
 Entering any value >= 1 sets Good variable to true
 Entering value < 0 also sets Good variable to true
13
PRIME NUMBER
EXAMPLE
 How can we test a number to see if it is prime?
 We are given numerical values between 1..100
 We need to see if it has any factors besides 1 and itself
 We need some nested if statements
 Test if input number is between 1..100
 If so, then test if 2,3,5,7 are factors of input number
 Then print out “prime” or “not prime”
14
PRIME NUMBER
EXAMPLE
// Check for prime numbers using a factoring approach
#include <iostream>
using namespace std;
int main()
{
// Local variable declarations
// Read input parameters
// Check input is valid
// Check if number is prime
// Print output
return 0;
}
15
For the first version
of program we just
write comments in
the main program to
explain our approach
PRIME NUMBER
EXAMPLE
// Check for prime numbers using a factoring approach
#include <iostream>
using namespace std;
int main()
{
// Local variable declarations
int Number = 0;
bool Prime = true;
// Read input parameters
cout << “Enter a number [1..100]:”;
cin >> Number;
16
For the second
version of program
we initialize variables
and read the input
value from user
PRIME NUMBER
EXAMPLE
…
cout << “Enter a number [1..100]:”;
cin >> Number;
// Check input is valid
if ((Number < 1) || (Number > 100))
cout << “Error: Number is out of rangen”;
else
{
// Check if number is prime
// Print output
}
17
For the next version
of the program we
add code to verify the
range of input value
PRIME NUMBER
EXAMPLE
…
// Check if number is prime
if (Number == 1) Prime = false;
if ((Number > 2) && (Number % 2 == 0)) Prime = false;
if ((Number > 3) && (Number % 3 == 0)) Prime = false;
if ((Number > 5) && (Number % 5 == 0)) Prime = false;
if ((Number > 7) && (Number % 7 == 0)) Prime = false;
// Print output
if (Prime)
cout << “Number “ << Number << “ IS primen”;
else
cout << “Number “ << Number << “ is NOT primen”;
… 18
In the final
version we finish
the prime number
calculation and
print the output
PRIME NUMBER
EXAMPLE
 How should we test the prime number program?
 Test the range checking code by entering values “on the
border” of the input range (e.g. 0,1,2 and 99,100,101)
 Test program with several values we know are prime
 Test program with several values we know are not prime
 To be really compulsive we could test all values between
1..100 and compare to known prime numbers
 What is wrong with this program?
 It only works for inputs between 1..100
 It will not “scale up” easily if we extend this input range
19
SUMMARY
 In this section we showed how if statements and if-else
statements can be nested inside each other to create more
complex paths through a program
 We also showed how proper indenting is important to read
and understand programs with nested if statements
 We have seen how Boolean variables can be used to store
true/false values in a program
 Finally, we used an incremental approach to create a
program for checking the factors of input numbers to see
if they are prime or not
20
EXAMPLE: WAGES.CPP
Write a C++ program that calculates weekly wages for hourly
employees.
 Regular hours 0 - 40 are paid at $10/hours.
 Overtime (> 40 hours per week) is paid at 150%

More Related Content

Similar to 10-Lec - Nested IF Statement.pptx

C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control StructureSokngim Sa
 
Control structure of c
Control structure of cControl structure of c
Control structure of cKomal Kotak
 
4. programing 101
4. programing 1014. programing 101
4. programing 101IEEE MIU SB
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programmingnmahi96
 
C Control Statements.docx
C Control Statements.docxC Control Statements.docx
C Control Statements.docxJavvajiVenkat
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
Chapter 4 flow control structures and arrays
Chapter 4 flow control structures and arraysChapter 4 flow control structures and arrays
Chapter 4 flow control structures and arrayssshhzap
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONvikram mahendra
 
C programming Control Structure.pptx
C programming Control Structure.pptxC programming Control Structure.pptx
C programming Control Structure.pptxDEEPAK948083
 
CHAPTER-3a.ppt
CHAPTER-3a.pptCHAPTER-3a.ppt
CHAPTER-3a.pptTekle12
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa Thapa
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2yasir_cesc
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while LoopJayBhavsar68
 

Similar to 10-Lec - Nested IF Statement.pptx (20)

C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
4. programing 101
4. programing 1014. programing 101
4. programing 101
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programming
 
C Control Statements.docx
C Control Statements.docxC Control Statements.docx
C Control Statements.docx
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Chapter 4 flow control structures and arrays
Chapter 4 flow control structures and arraysChapter 4 flow control structures and arrays
Chapter 4 flow control structures and arrays
 
If
IfIf
If
 
ICP - Lecture 7 and 8
ICP - Lecture 7 and 8ICP - Lecture 7 and 8
ICP - Lecture 7 and 8
 
Control Statement programming
Control Statement programmingControl Statement programming
Control Statement programming
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
 
CalStatementsNAV2013
CalStatementsNAV2013CalStatementsNAV2013
CalStatementsNAV2013
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHON
 
C programming Control Structure.pptx
C programming Control Structure.pptxC programming Control Structure.pptx
C programming Control Structure.pptx
 
CHAPTER-3a.ppt
CHAPTER-3a.pptCHAPTER-3a.ppt
CHAPTER-3a.ppt
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
 
Ch04
Ch04Ch04
Ch04
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
 

More from AqeelAbbas94

lecture_5 (2).ppt hjhrrgjbgrmgrhbgrgghjd
lecture_5 (2).ppt hjhrrgjbgrmgrhbgrgghjdlecture_5 (2).ppt hjhrrgjbgrmgrhbgrgghjd
lecture_5 (2).ppt hjhrrgjbgrmgrhbgrgghjdAqeelAbbas94
 
1-Lec - Introduction vhvv,vbvv,v (2).ppt
1-Lec - Introduction vhvv,vbvv,v (2).ppt1-Lec - Introduction vhvv,vbvv,v (2).ppt
1-Lec - Introduction vhvv,vbvv,v (2).pptAqeelAbbas94
 
2-Lec - History of OOP and Java (1) .ppt
2-Lec - History of OOP and Java  (1) .ppt2-Lec - History of OOP and Java  (1) .ppt
2-Lec - History of OOP and Java (1) .pptAqeelAbbas94
 
Lecture-32-33.pptx
Lecture-32-33.pptxLecture-32-33.pptx
Lecture-32-33.pptxAqeelAbbas94
 
use_case+use_case description.pptx
use_case+use_case description.pptxuse_case+use_case description.pptx
use_case+use_case description.pptxAqeelAbbas94
 
555e81217b39f1c1262b33d0.ppt
555e81217b39f1c1262b33d0.ppt555e81217b39f1c1262b33d0.ppt
555e81217b39f1c1262b33d0.pptAqeelAbbas94
 
12-Lec - Repetition For Loop.pptx
12-Lec - Repetition For Loop.pptx12-Lec - Repetition For Loop.pptx
12-Lec - Repetition For Loop.pptxAqeelAbbas94
 
wepik-exploring-the-robust-features-of-samsung-health-app-enhancing-well-bein...
wepik-exploring-the-robust-features-of-samsung-health-app-enhancing-well-bein...wepik-exploring-the-robust-features-of-samsung-health-app-enhancing-well-bein...
wepik-exploring-the-robust-features-of-samsung-health-app-enhancing-well-bein...AqeelAbbas94
 
19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.ppt19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.pptAqeelAbbas94
 
Your Title goes Here.pptx
Your Title goes Here.pptxYour Title goes Here.pptx
Your Title goes Here.pptxAqeelAbbas94
 
5-Lec - Datatypes.ppt
5-Lec - Datatypes.ppt5-Lec - Datatypes.ppt
5-Lec - Datatypes.pptAqeelAbbas94
 

More from AqeelAbbas94 (20)

lecture_5 (2).ppt hjhrrgjbgrmgrhbgrgghjd
lecture_5 (2).ppt hjhrrgjbgrmgrhbgrgghjdlecture_5 (2).ppt hjhrrgjbgrmgrhbgrgghjd
lecture_5 (2).ppt hjhrrgjbgrmgrhbgrgghjd
 
1-Lec - Introduction vhvv,vbvv,v (2).ppt
1-Lec - Introduction vhvv,vbvv,v (2).ppt1-Lec - Introduction vhvv,vbvv,v (2).ppt
1-Lec - Introduction vhvv,vbvv,v (2).ppt
 
2-Lec - History of OOP and Java (1) .ppt
2-Lec - History of OOP and Java  (1) .ppt2-Lec - History of OOP and Java  (1) .ppt
2-Lec - History of OOP and Java (1) .ppt
 
Lecture-32-33.pptx
Lecture-32-33.pptxLecture-32-33.pptx
Lecture-32-33.pptx
 
blue.pptx
blue.pptxblue.pptx
blue.pptx
 
use_case+use_case description.pptx
use_case+use_case description.pptxuse_case+use_case description.pptx
use_case+use_case description.pptx
 
555e81217b39f1c1262b33d0.ppt
555e81217b39f1c1262b33d0.ppt555e81217b39f1c1262b33d0.ppt
555e81217b39f1c1262b33d0.ppt
 
12-Lec - Repetition For Loop.pptx
12-Lec - Repetition For Loop.pptx12-Lec - Repetition For Loop.pptx
12-Lec - Repetition For Loop.pptx
 
hexagon.pptx
hexagon.pptxhexagon.pptx
hexagon.pptx
 
Lecture1.ppt
Lecture1.pptLecture1.ppt
Lecture1.ppt
 
wepik-exploring-the-robust-features-of-samsung-health-app-enhancing-well-bein...
wepik-exploring-the-robust-features-of-samsung-health-app-enhancing-well-bein...wepik-exploring-the-robust-features-of-samsung-health-app-enhancing-well-bein...
wepik-exploring-the-robust-features-of-samsung-health-app-enhancing-well-bein...
 
lecture56.ppt
lecture56.pptlecture56.ppt
lecture56.ppt
 
04.ppt
04.ppt04.ppt
04.ppt
 
19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.ppt19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.ppt
 
SelectionSort.ppt
SelectionSort.pptSelectionSort.ppt
SelectionSort.ppt
 
Lecture2 (1).ppt
Lecture2 (1).pptLecture2 (1).ppt
Lecture2 (1).ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
Your Title goes Here.pptx
Your Title goes Here.pptxYour Title goes Here.pptx
Your Title goes Here.pptx
 
SE_models_1.ppt
SE_models_1.pptSE_models_1.ppt
SE_models_1.ppt
 
5-Lec - Datatypes.ppt
5-Lec - Datatypes.ppt5-Lec - Datatypes.ppt
5-Lec - Datatypes.ppt
 

Recently uploaded

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 

Recently uploaded (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 

10-Lec - Nested IF Statement.pptx

  • 2. NESTED IF STATEMENTS We can have two or more if statements inside each other to check multiple conditions  These are called nested if statements Nested if statements can be used to test more than one condition Use indentation to reflect nesting and aid readability  Typically indent 3-4 spaces or one tab Need to take care when matching up { } brackets  This way you can decipher the nesting of conditions 2
  • 3. NESTED IF STATEMENTS if ( logical expression1 ) { if ( logical expression2 ) { // Statements to execute if expressions1 and expression2 are true } else { // Statements to execute if expression1 true and expression2 false } } else { // Statements to execute if expression1 false } 3
  • 4. FLOWCHART FOR A NESTED IF STATEMENT 4
  • 5. NESTED IF CODE // Determine loan qualification if (employed == ‘y’) { if (recentGrad == ‘y’) { cout << “You qualify!” } } Note: this could be done with one if and two conditions. 5
  • 6. NESTED IF CODE // Determine loan qualification using one if and //two conditions if (employed == ‘y’ && recentGrad == ‘y’) { cout << “You qualify!” } 6
  • 7. NESTED IF STATEMENTS // Simple nested if example cin >> a >> b; if (a < b) { cout << “A is smaller than Bn”; if ((a > 0) && (b > 0)) cout << “A and B are both positiven”; else cout << “A or B or both are negativen”; } 7
  • 8. NESTED IF STATEMENTS // Ugly nested if example if (a > 0) { if (b < 0) { a = 3 * b; c = a + b; } } else { a = 2 * a; c = b / a; }  It is hard to see what condition the else code goes with 8
  • 9. NESTED IF STATEMENTS // Pretty nested if example if (a > 0) { if (b < 0) { a = 3 * b; c = a + b; } } else { a = 2 * a; c = b / a; } 9
  • 10. BOOLEAN VARIABLES  In C++ we can store true/false values in Boolean variables  The constants “true” and “false” can be used to initialize these variables  bool Done = true;  bool Quit = false;  Boolean expressions can also be used to initialize these variables  bool Positive = (a >= 0);  bool Negative = (b < 0); 10
  • 11. BOOLEAN VARIABLES  Boolean variables and true/false constants can also be used in logical expressions  (Done == true) is true  (Quit != true) is true  (Done == Quit) is false  (true == Positive) is true  ((a < b) == false) is false  (Negative) is false 11
  • 12. BOOLEAN VARIABLES  Internally C++ stores Boolean variables as integers  0 is normally used for false  1 is normally used for true  Any non-zero value is also considered true  It is considered “bad programming style” to use integers instead of true/false  bool Good = 0;  bool Bad = 1;  bool Ugly = a; 12
  • 13. BOOLEAN VARIABLES  Integers are used when writing Boolean values  cout << Good will print 0  cout << Bad will print 1  cout << Ugly will also print 1  Integers are also used when reading Boolean values  cin >> Good;  Entering 0 sets Good variable to false  Entering any value >= 1 sets Good variable to true  Entering value < 0 also sets Good variable to true 13
  • 14. PRIME NUMBER EXAMPLE  How can we test a number to see if it is prime?  We are given numerical values between 1..100  We need to see if it has any factors besides 1 and itself  We need some nested if statements  Test if input number is between 1..100  If so, then test if 2,3,5,7 are factors of input number  Then print out “prime” or “not prime” 14
  • 15. PRIME NUMBER EXAMPLE // Check for prime numbers using a factoring approach #include <iostream> using namespace std; int main() { // Local variable declarations // Read input parameters // Check input is valid // Check if number is prime // Print output return 0; } 15 For the first version of program we just write comments in the main program to explain our approach
  • 16. PRIME NUMBER EXAMPLE // Check for prime numbers using a factoring approach #include <iostream> using namespace std; int main() { // Local variable declarations int Number = 0; bool Prime = true; // Read input parameters cout << “Enter a number [1..100]:”; cin >> Number; 16 For the second version of program we initialize variables and read the input value from user
  • 17. PRIME NUMBER EXAMPLE … cout << “Enter a number [1..100]:”; cin >> Number; // Check input is valid if ((Number < 1) || (Number > 100)) cout << “Error: Number is out of rangen”; else { // Check if number is prime // Print output } 17 For the next version of the program we add code to verify the range of input value
  • 18. PRIME NUMBER EXAMPLE … // Check if number is prime if (Number == 1) Prime = false; if ((Number > 2) && (Number % 2 == 0)) Prime = false; if ((Number > 3) && (Number % 3 == 0)) Prime = false; if ((Number > 5) && (Number % 5 == 0)) Prime = false; if ((Number > 7) && (Number % 7 == 0)) Prime = false; // Print output if (Prime) cout << “Number “ << Number << “ IS primen”; else cout << “Number “ << Number << “ is NOT primen”; … 18 In the final version we finish the prime number calculation and print the output
  • 19. PRIME NUMBER EXAMPLE  How should we test the prime number program?  Test the range checking code by entering values “on the border” of the input range (e.g. 0,1,2 and 99,100,101)  Test program with several values we know are prime  Test program with several values we know are not prime  To be really compulsive we could test all values between 1..100 and compare to known prime numbers  What is wrong with this program?  It only works for inputs between 1..100  It will not “scale up” easily if we extend this input range 19
  • 20. SUMMARY  In this section we showed how if statements and if-else statements can be nested inside each other to create more complex paths through a program  We also showed how proper indenting is important to read and understand programs with nested if statements  We have seen how Boolean variables can be used to store true/false values in a program  Finally, we used an incremental approach to create a program for checking the factors of input numbers to see if they are prime or not 20
  • 21. EXAMPLE: WAGES.CPP Write a C++ program that calculates weekly wages for hourly employees.  Regular hours 0 - 40 are paid at $10/hours.  Overtime (> 40 hours per week) is paid at 150%