SlideShare a Scribd company logo
1 of 34
Download to read offline
Programming
Fundamentals
By
Adnan Waheed
University of Narowal
Control Structure
(Selection Statements)
Lecture No. 12
Tuesday, November 21, 2023
Avoiding Bugs by Avoiding Partially
Understood Concepts and
Techniques
• Must use concepts and techniques
correctly;
– Otherwise solution will be either incorrect or
deficient
• If you do not understand a concept or
technique completely
– Don’t use it
– Save yourself an enormous amount of
debugging time
C++ Programming: Program Design Including Data Structures, Fifth Edition 2
Input Failure and the if
Statement
• If input stream enters a fail state
– All subsequent input statements associated
with that stream are ignored
– Program continues to execute
– May produce erroneous results
• Can use if statements to check status of
input stream
• If stream enters the fail state, include
instructions that stop program execution
C++ Programming: Program Design Including Data Structures, Fifth Edition 3
Confusion Between the Equality
(==) and Assignment (=) Operators
• C++ allows you to use any expression that
can be evaluated to either true or false
as an expression in the if statement:
if (x = 5)
cout << "The value is five." << endl;
• The appearance of = in place of ==
resembles a silent killer
– It is not a syntax error
– It is a logical error
C++ Programming: Program Design Including Data Structures, Fifth Edition 4
Program Style and Form
(Revisited): Indentation
• If your program is properly indented
– Spot and fix errors quickly
– Show the natural grouping of statements
• Insert a blank line between statements that
are naturally separate
• Two commonly used styles for placing braces
– On a line by themselves
– Or left brace is placed after the expression, and
the right brace is on a line by itself
C++ Programming: Program Design Including Data Structures, Fifth Edition 5
Using Pseudocode to Develop,
Test, and Debug a Program
• Pseudocode, or just pseudo
– Informal mixture of C++ and ordinary
language
– Helps you quickly develop the correct
structure of the program and avoid making
common errors
• Use a wide range of values in a walk-
through to evaluate the program
C++ Programming: Program Design Including Data Structures, Fifth Edition 6
switch Structures
• switch structure:
alternate to if-else
• switch (integral)
expression is evaluated
first
• Value of the expression
determines which
corresponding action is
taken
• Expression is sometimes
called the selector
C++ Programming: Program Design Including Data Structures, Fifth Edition 7
switch Structures
• Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
C++ Programming: Program Design Including Data Structures, Fifth Edition 8
•The switch expression is
evaluated once
•The value of the expression is
compared with the values of
each case
•If there is a match, the
associated block of code is
executed
•The break and default keywords
are optional
switch Structures (cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition 9
Switch Example
• The example below uses the weekday number to calculate the weekday
name:
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break; // Outputs "Thursday" (day 4)
C++ Programming: Program Design Including Data Structures, Fifth Edition 10
The break Keyword
C++ Programming: Program Design Including Data Structures, Fifth Edition 11
• When C++ reaches a break keyword, it breaks out of the switch
block.
• This will stop the execution of more code and case testing inside
the block.
• When a match is found, and the job is done, it's time for a break.
There is no need for more testing.
The default Keyword
C++ Programming: Program Design Including Data Structures, Fifth Edition 12
The default keyword specifies some code to run if there is no case match:
int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}
// Outputs "Looking forward to the Weekend.
switch Structures (cont'd.)
C++ Programming: Program Design Including Data Structures, Fifth Edition 13
C++ Programming: Program Design Including Data Structures, Fifth Edition 14
Output = ?
C++ Programming: Program Design Including Data Structures, Fifth Edition 15
Avoiding Bugs by Avoiding Partially
Understood Concepts and
Techniques: Revisited
• To output results correctly
– The switch structure must include a break
statement after each cout statement
C++ Programming: Program Design Including Data Structures, Fifth Edition 16
COMPLETE EXAMPLE @
HOME FOR PRACTICE OF
STUDENTS
C++ Programming: Program Design Including Data Structures, Fifth Edition 17
Programming Example: Cable
Company Billing
• This programming example calculates a
customer’s bill for a local cable company
• There are two types of customers:
– Residential
– Business
• Two rates for calculating a cable bill:
– One for residential customers
– One for business customers
C++ Programming: Program Design Including Data Structures, Fifth Edition 18
Programming Example: Rates
• For residential customer:
– Bill processing fee: $4.50
– Basic service fee: $20.50
– Premium channel: $7.50 per channel
• For business customer:
– Bill processing fee: $15.00
– Basic service fee: $75.00 for first 10
connections/$5.00 for each additional one
– Premium channel cost: $50.00 per channel for
any number of connections
C++ Programming: Program Design Including Data Structures, Fifth Edition 19
Programming Example:
Requirements
• Ask user for account number and
customer code
• Assume R or r stands for residential
customer and B or b stands for business
customer
C++ Programming: Program Design Including Data Structures, Fifth Edition 20
Programming Example: Input and
Output
• Input:
– Customer account number
– Customer code
– Number of premium channels
– For business customers, number of basic
service connections
• Output:
– Customer’s account number
– Billing amount
C++ Programming: Program Design Including Data Structures, Fifth Edition 21
Programming Example: Program
Analysis
• Purpose: calculate and print billing amount
• Calculating billing amount requires:
– Customer for whom the billing amount is
calculated (residential or business)
– Number of premium channels to which the
customer subscribes
• For a business customer, you need:
– Number of basic service connections
– Number of premium channels
C++ Programming: Program Design Including Data Structures, Fifth Edition 22
Programming Example: Program
Analysis (cont'd.)
• Data needed to calculate the bill, such as
bill processing fees and the cost of a
premium channel, are known quantities
• The program should print the billing
amount to two decimal places
C++ Programming: Program Design Including Data Structures, Fifth Edition 23
Programming Example: Algorithm
Design
• Set precision to two decimal places
• Prompt user for account number and
customer type
• If customer type is R or r
– Prompt user for number of premium channels
– Compute and print the bill
• If customer type is B or b
– Prompt user for number of basic service
connections and number of premium channels
– Compute and print the bill
C++ Programming: Program Design Including Data Structures, Fifth Edition 24
Programming Example: Variables
and Named Constants
C++ Programming: Program Design Including Data Structures, Fifth Edition 25
Programming Example:
Formulas
Billing for residential customers:
amountDue = RES_BILL_PROC_FEES +
RES_BASIC_SERV_COST
+ numOfPremChannels *
RES_COST_PREM_CHANNEL;
C++ Programming: Program Design Including Data Structures, Fifth Edition 26
Programming Example: Formulas
(cont'd.)
Billing for business customers:
if (numOfBasicServConn <= 10)
amountDue = BUS_BILL_PROC_FEES +
BUS_BASIC_SERV_COST
+ numOfPremChannels *
BUS_COST_PREM_CHANNEL;
else
amountDue = BUS_BILL_PROC_FEES +
BUS_BASIC_SERV_COST
+ (numOfBasicServConn - 10)
* BUS_BASIC_CONN_COST
+ numOfPremChannels *
BUS_COST_PREM_CHANNEL;
C++ Programming: Program Design Including Data Structures, Fifth Edition 27
Programming Example: Main
Algorithm
1. Output floating-point numbers in fixed
decimal with decimal point and trailing zeros
– Output floating-point numbers with two decimal
places and set the precision to two decimal
places
2. Prompt user to enter account number
3. Get customer account number
4. Prompt user to enter customer code
5. Get customer code
C++ Programming: Program Design Including Data Structures, Fifth Edition 28
Programming Example: Main
Algorithm (cont'd.)
6. If the customer code is r or R,
– Prompt user to enter number of premium
channels
– Get the number of premium channels
– Calculate the billing amount
– Print account number and billing amount
C++ Programming: Program Design Including Data Structures, Fifth Edition 29
Programming Example: Main
Algorithm (cont'd.)
7. If customer code is b or B,
– Prompt user to enter number of basic
service connections
– Get number of basic service connections
– Prompt user to enter number of premium
channels
– Get number of premium channels
– Calculate billing amount
– Print account number and billing amount
C++ Programming: Program Design Including Data Structures, Fifth Edition 30
Programming Example: Main
Algorithm (cont'd.)
8. If customer code is other than r, R, b,
or B, output an error message
C++ Programming: Program Design Including Data Structures, Fifth Edition 31
Summary
• Control structures alter normal control flow
• Most common control structures are
selection and repetition
• Relational operators: ==, <, <=, >, >=, !=
• Logical expressions evaluate to 1 (true)
or 0 (false)
• Logical operators: ! (not), && (and), ||
(or)
C++ Programming: Program Design Including Data Structures, Fifth Edition 32
Summary (cont'd.)
• Two selection structures: one-way selection
and two-way selection
• The expression in an if or if...else
structure is usually a logical expression
• No stand-alone else statement in C++
– Every else has a related if
• A sequence of statements enclosed between
braces, { and }, is called a compound
statement or block of statements
C++ Programming: Program Design Including Data Structures, Fifth Edition 33
Summary (cont'd.)
• Using assignment in place of the equality
operator creates a semantic error
• switch structure handles multiway
selection
• break statement ends switch statement
• Use assert to terminate a program if
certain conditions are not met
C++ Programming: Program Design Including Data Structures, Fifth Edition 34

More Related Content

Similar to Programming Fundamentals: Control Structures and Cable Billing Program

Md university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newMd university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newLast7693
 
Md university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newMd university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newscottbrownnn
 
Computer programming all chapters
Computer programming all chaptersComputer programming all chapters
Computer programming all chaptersIbrahim Elewah
 
ch01_an overview of computers and programming languages
ch01_an overview of computers and programming languagesch01_an overview of computers and programming languages
ch01_an overview of computers and programming languagesLiemLe21
 
9781285852744 ppt ch12
9781285852744 ppt ch129781285852744 ppt ch12
9781285852744 ppt ch12Terry Yoast
 
U19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).pptU19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).pptManivannan837728
 
Debugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsDebugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsPlatonov Sergey
 
Csc1100 lecture03 ch03-pt2-s14
Csc1100 lecture03 ch03-pt2-s14Csc1100 lecture03 ch03-pt2-s14
Csc1100 lecture03 ch03-pt2-s14IIUM
 
Csc1100 lecture03 ch03-pt2-s14
Csc1100 lecture03 ch03-pt2-s14Csc1100 lecture03 ch03-pt2-s14
Csc1100 lecture03 ch03-pt2-s14IIUM
 
Object oriented programming 12 programming steps in cpp and example
Object oriented programming 12 programming steps in cpp and exampleObject oriented programming 12 programming steps in cpp and example
Object oriented programming 12 programming steps in cpp and exampleVaibhav Khanna
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++cpjcollege
 
COMP 122 Entire Course NEW
COMP 122 Entire Course NEWCOMP 122 Entire Course NEW
COMP 122 Entire Course NEWshyamuopeight
 
Basic of c++ programming
Basic of c++ programmingBasic of c++ programming
Basic of c++ programmingTalha Mughal
 
Fundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxFundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxVigneshkumar Ponnusamy
 
C++ Programming Chapter 01
C++ Programming Chapter 01C++ Programming Chapter 01
C++ Programming Chapter 01Sourng Seng
 

Similar to Programming Fundamentals: Control Structures and Cable Billing Program (20)

Md university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newMd university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab new
 
Md university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newMd university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab new
 
c++ referesher 1.pdf
c++ referesher 1.pdfc++ referesher 1.pdf
c++ referesher 1.pdf
 
Computer programming all chapters
Computer programming all chaptersComputer programming all chapters
Computer programming all chapters
 
ch01_an overview of computers and programming languages
ch01_an overview of computers and programming languagesch01_an overview of computers and programming languages
ch01_an overview of computers and programming languages
 
9781285852744 ppt ch12
9781285852744 ppt ch129781285852744 ppt ch12
9781285852744 ppt ch12
 
U19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).pptU19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).ppt
 
Debugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsDebugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template Metaprograms
 
Csc1100 lecture03 ch03-pt2-s14
Csc1100 lecture03 ch03-pt2-s14Csc1100 lecture03 ch03-pt2-s14
Csc1100 lecture03 ch03-pt2-s14
 
Csc1100 lecture03 ch03-pt2-s14
Csc1100 lecture03 ch03-pt2-s14Csc1100 lecture03 ch03-pt2-s14
Csc1100 lecture03 ch03-pt2-s14
 
C++ ch1
C++ ch1C++ ch1
C++ ch1
 
Object oriented programming 12 programming steps in cpp and example
Object oriented programming 12 programming steps in cpp and exampleObject oriented programming 12 programming steps in cpp and example
Object oriented programming 12 programming steps in cpp and example
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++
 
COMP 122 Entire Course NEW
COMP 122 Entire Course NEWCOMP 122 Entire Course NEW
COMP 122 Entire Course NEW
 
Basic of c++ programming
Basic of c++ programmingBasic of c++ programming
Basic of c++ programming
 
Intro
IntroIntro
Intro
 
Fundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxFundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptx
 
Lesson 5.2 logical operators
Lesson 5.2 logical operatorsLesson 5.2 logical operators
Lesson 5.2 logical operators
 
C++ Programming Chapter 01
C++ Programming Chapter 01C++ Programming Chapter 01
C++ Programming Chapter 01
 
C programming
C programmingC programming
C programming
 

Recently uploaded

Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 

Recently uploaded (20)

Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 

Programming Fundamentals: Control Structures and Cable Billing Program

  • 1. Programming Fundamentals By Adnan Waheed University of Narowal Control Structure (Selection Statements) Lecture No. 12 Tuesday, November 21, 2023
  • 2. Avoiding Bugs by Avoiding Partially Understood Concepts and Techniques • Must use concepts and techniques correctly; – Otherwise solution will be either incorrect or deficient • If you do not understand a concept or technique completely – Don’t use it – Save yourself an enormous amount of debugging time C++ Programming: Program Design Including Data Structures, Fifth Edition 2
  • 3. Input Failure and the if Statement • If input stream enters a fail state – All subsequent input statements associated with that stream are ignored – Program continues to execute – May produce erroneous results • Can use if statements to check status of input stream • If stream enters the fail state, include instructions that stop program execution C++ Programming: Program Design Including Data Structures, Fifth Edition 3
  • 4. Confusion Between the Equality (==) and Assignment (=) Operators • C++ allows you to use any expression that can be evaluated to either true or false as an expression in the if statement: if (x = 5) cout << "The value is five." << endl; • The appearance of = in place of == resembles a silent killer – It is not a syntax error – It is a logical error C++ Programming: Program Design Including Data Structures, Fifth Edition 4
  • 5. Program Style and Form (Revisited): Indentation • If your program is properly indented – Spot and fix errors quickly – Show the natural grouping of statements • Insert a blank line between statements that are naturally separate • Two commonly used styles for placing braces – On a line by themselves – Or left brace is placed after the expression, and the right brace is on a line by itself C++ Programming: Program Design Including Data Structures, Fifth Edition 5
  • 6. Using Pseudocode to Develop, Test, and Debug a Program • Pseudocode, or just pseudo – Informal mixture of C++ and ordinary language – Helps you quickly develop the correct structure of the program and avoid making common errors • Use a wide range of values in a walk- through to evaluate the program C++ Programming: Program Design Including Data Structures, Fifth Edition 6
  • 7. switch Structures • switch structure: alternate to if-else • switch (integral) expression is evaluated first • Value of the expression determines which corresponding action is taken • Expression is sometimes called the selector C++ Programming: Program Design Including Data Structures, Fifth Edition 7
  • 8. switch Structures • Syntax switch(expression) { case x: // code block break; case y: // code block break; default: // code block C++ Programming: Program Design Including Data Structures, Fifth Edition 8 •The switch expression is evaluated once •The value of the expression is compared with the values of each case •If there is a match, the associated block of code is executed •The break and default keywords are optional
  • 9. switch Structures (cont'd.) C++ Programming: Program Design Including Data Structures, Fifth Edition 9
  • 10. Switch Example • The example below uses the weekday number to calculate the weekday name: int day = 4; switch (day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; case 3: cout << "Wednesday"; break; case 4: cout << "Thursday"; break; case 5: cout << "Friday"; break; case 6: cout << "Saturday"; break; case 7: cout << "Sunday"; break; // Outputs "Thursday" (day 4) C++ Programming: Program Design Including Data Structures, Fifth Edition 10
  • 11. The break Keyword C++ Programming: Program Design Including Data Structures, Fifth Edition 11 • When C++ reaches a break keyword, it breaks out of the switch block. • This will stop the execution of more code and case testing inside the block. • When a match is found, and the job is done, it's time for a break. There is no need for more testing.
  • 12. The default Keyword C++ Programming: Program Design Including Data Structures, Fifth Edition 12 The default keyword specifies some code to run if there is no case match: int day = 4; switch (day) { case 6: cout << "Today is Saturday"; break; case 7: cout << "Today is Sunday"; break; default: cout << "Looking forward to the Weekend"; } // Outputs "Looking forward to the Weekend.
  • 13. switch Structures (cont'd.) C++ Programming: Program Design Including Data Structures, Fifth Edition 13
  • 14. C++ Programming: Program Design Including Data Structures, Fifth Edition 14
  • 15. Output = ? C++ Programming: Program Design Including Data Structures, Fifth Edition 15
  • 16. Avoiding Bugs by Avoiding Partially Understood Concepts and Techniques: Revisited • To output results correctly – The switch structure must include a break statement after each cout statement C++ Programming: Program Design Including Data Structures, Fifth Edition 16
  • 17. COMPLETE EXAMPLE @ HOME FOR PRACTICE OF STUDENTS C++ Programming: Program Design Including Data Structures, Fifth Edition 17
  • 18. Programming Example: Cable Company Billing • This programming example calculates a customer’s bill for a local cable company • There are two types of customers: – Residential – Business • Two rates for calculating a cable bill: – One for residential customers – One for business customers C++ Programming: Program Design Including Data Structures, Fifth Edition 18
  • 19. Programming Example: Rates • For residential customer: – Bill processing fee: $4.50 – Basic service fee: $20.50 – Premium channel: $7.50 per channel • For business customer: – Bill processing fee: $15.00 – Basic service fee: $75.00 for first 10 connections/$5.00 for each additional one – Premium channel cost: $50.00 per channel for any number of connections C++ Programming: Program Design Including Data Structures, Fifth Edition 19
  • 20. Programming Example: Requirements • Ask user for account number and customer code • Assume R or r stands for residential customer and B or b stands for business customer C++ Programming: Program Design Including Data Structures, Fifth Edition 20
  • 21. Programming Example: Input and Output • Input: – Customer account number – Customer code – Number of premium channels – For business customers, number of basic service connections • Output: – Customer’s account number – Billing amount C++ Programming: Program Design Including Data Structures, Fifth Edition 21
  • 22. Programming Example: Program Analysis • Purpose: calculate and print billing amount • Calculating billing amount requires: – Customer for whom the billing amount is calculated (residential or business) – Number of premium channels to which the customer subscribes • For a business customer, you need: – Number of basic service connections – Number of premium channels C++ Programming: Program Design Including Data Structures, Fifth Edition 22
  • 23. Programming Example: Program Analysis (cont'd.) • Data needed to calculate the bill, such as bill processing fees and the cost of a premium channel, are known quantities • The program should print the billing amount to two decimal places C++ Programming: Program Design Including Data Structures, Fifth Edition 23
  • 24. Programming Example: Algorithm Design • Set precision to two decimal places • Prompt user for account number and customer type • If customer type is R or r – Prompt user for number of premium channels – Compute and print the bill • If customer type is B or b – Prompt user for number of basic service connections and number of premium channels – Compute and print the bill C++ Programming: Program Design Including Data Structures, Fifth Edition 24
  • 25. Programming Example: Variables and Named Constants C++ Programming: Program Design Including Data Structures, Fifth Edition 25
  • 26. Programming Example: Formulas Billing for residential customers: amountDue = RES_BILL_PROC_FEES + RES_BASIC_SERV_COST + numOfPremChannels * RES_COST_PREM_CHANNEL; C++ Programming: Program Design Including Data Structures, Fifth Edition 26
  • 27. Programming Example: Formulas (cont'd.) Billing for business customers: if (numOfBasicServConn <= 10) amountDue = BUS_BILL_PROC_FEES + BUS_BASIC_SERV_COST + numOfPremChannels * BUS_COST_PREM_CHANNEL; else amountDue = BUS_BILL_PROC_FEES + BUS_BASIC_SERV_COST + (numOfBasicServConn - 10) * BUS_BASIC_CONN_COST + numOfPremChannels * BUS_COST_PREM_CHANNEL; C++ Programming: Program Design Including Data Structures, Fifth Edition 27
  • 28. Programming Example: Main Algorithm 1. Output floating-point numbers in fixed decimal with decimal point and trailing zeros – Output floating-point numbers with two decimal places and set the precision to two decimal places 2. Prompt user to enter account number 3. Get customer account number 4. Prompt user to enter customer code 5. Get customer code C++ Programming: Program Design Including Data Structures, Fifth Edition 28
  • 29. Programming Example: Main Algorithm (cont'd.) 6. If the customer code is r or R, – Prompt user to enter number of premium channels – Get the number of premium channels – Calculate the billing amount – Print account number and billing amount C++ Programming: Program Design Including Data Structures, Fifth Edition 29
  • 30. Programming Example: Main Algorithm (cont'd.) 7. If customer code is b or B, – Prompt user to enter number of basic service connections – Get number of basic service connections – Prompt user to enter number of premium channels – Get number of premium channels – Calculate billing amount – Print account number and billing amount C++ Programming: Program Design Including Data Structures, Fifth Edition 30
  • 31. Programming Example: Main Algorithm (cont'd.) 8. If customer code is other than r, R, b, or B, output an error message C++ Programming: Program Design Including Data Structures, Fifth Edition 31
  • 32. Summary • Control structures alter normal control flow • Most common control structures are selection and repetition • Relational operators: ==, <, <=, >, >=, != • Logical expressions evaluate to 1 (true) or 0 (false) • Logical operators: ! (not), && (and), || (or) C++ Programming: Program Design Including Data Structures, Fifth Edition 32
  • 33. Summary (cont'd.) • Two selection structures: one-way selection and two-way selection • The expression in an if or if...else structure is usually a logical expression • No stand-alone else statement in C++ – Every else has a related if • A sequence of statements enclosed between braces, { and }, is called a compound statement or block of statements C++ Programming: Program Design Including Data Structures, Fifth Edition 33
  • 34. Summary (cont'd.) • Using assignment in place of the equality operator creates a semantic error • switch structure handles multiway selection • break statement ends switch statement • Use assert to terminate a program if certain conditions are not met C++ Programming: Program Design Including Data Structures, Fifth Edition 34