SlideShare a Scribd company logo
1 of 21
Muhammad Uzair Rasheed

2009-CPE-03

UCE&T BZU MULTAN

        •adams@calvin.edu
C++ Loop Statements

    Repetition Revisited
Problem
Using OCD, design and implement a function
 that, given a menu, its first valid choice, and
 its last valid choice, displays that menu,
 reads a choice from the user, and returns a
 value guaranteed to be (i) a valid choice from
 the menu, and (ii) a choice chosen by the
 user.
You may assume that the valid menu choices
 form a continuous sequence.
Preliminary Analysis
The tricky part is that the function must return
  a value that
(i) is a valid menu choice; and
(ii) was chosen by the user.
One way to accomplish both goals is to use a
 loop that displays the menu, reads the
 user’s choice, checks its validity, and if it is
 not valid, gives them another chance...
Behavior
Our function should receive a menu, its first
 valid choice and its last valid choice. It
 should repeatedly display the menu, read
 the user’s choice, so long as the user’s
 choice is invalid. It should then return the
 user’s choice.
Objects
Description     Type       Kind       Name
menu            string    constant    MENU
first valid     char      variable    firstChoice
  choice
last valid      char      variable    lastChoice
  choice
user’s choice    char      variable    choice
Operations
Description       Predefined? Library?   Name
display strings      yes      iostream     <<
read a char          yes      iostream     >>
check validity       no       built-in     <=, &&
repeat steps         yes      built-in     ?
terminate loop       yes      built-in     ?
return a char        yes      built-in    return
Algorithm
0. Receive MENU, firstChoice, lastChoice.
1. Loop
  a. Display MENU via cout.
  b. Read choice from cin.
  c. If firstChoice <= choice and choice <= lastChoice:
       terminate repetition.
  End loop.
2. Return choice.
Organization
Note that our algorithm terminates the
 repetition at the bottom of the loop.
To code such loops conveniently and
  readably, C++ provides the do loop.
Coding
char GetValidMenuChoice(const string MENU,
                           char firstChoice, char lastChoice)
{
   char choice;
   do
   {
      cout << MENU;
      cin >> choice;
   }
   while (choice < firstChoice || choice > lastChoice);

    return choice;
}
Discussion
The do loop tests its condition at the end of the
  loop, making it useful for any problem in
  which the body of the loop must be
  performed at least once.
This function seems general enough to be
  reuseable by any menu-using program,        so
  it should be stored in a library.
Using the Function
Once our function is stored in a library, a
 programmer can write something like this:

#include “Menu.h”

int main()
{
   const string MENU =
      “Please enter:n”
      “ a - to do thisn”
      “ b - to do thatn”
      “ c - to do the othern”
      “--> “;

    char choice = GetValidMenuChoice(MENU, ‘a’, ‘c’);

    // ...
}
Testing
Please enter:
 a - to do this
 b - to do that
 c - to do the other
--> s
Please enter:
 a - to do this
 b - to do that
 c - to do the other
--> q
Please enter:
 a - to do this
 b - to do that
 c - to do the other
--> a
...
Note
If we wish to display an error message, that
   changes our algorithm...
Such a message should only be displayed if the
 user enters an invalid value, but should be
 displayed each time they do so.
Our algorithm must be adapted accordingly.
Algorithm (revised)
0. Receive MENU, firstChoice, lastChoice.
1. Loop
  a. Display MENU via cout.
  b. Read choice from cin.
  c. If firstChoice <= choice and choice <= lastChoice:
       terminate repetition.
  d. Display error message.
  End loop.
2. Return choice.
Organization
Our algorithm no longer terminates the
 repetition at the bottom of the loop.
Instead, it terminates repetition in the middle of
  the loop, suggesting a forever loop.
Which loop is best used depends on where
 execution leaves the loop in one’s algorithm.
Coding
char GetValidMenuChoice(const string MENU,
                           char firstChoice, char lastChoice)
{
   char choice;
   for (;;)
   {
      cout << MENU;
      cin >> choice;

        if (choice >= firstChoice && choice <= lastChoice)
           break;

        cerr << “n*** Invalid menu choice: ’“ << choice
             << “’ entered.n” << endl;
    }

    return choice;
}
Discussion
C++ provides a variety of loops:
  – The for loop for counting problems
  – The while loop for problems where repetition
    should be terminated at the loop’s beginning.
  – The do loop for problems where repetition should
    be terminated at the loop’s end.
  – The forever loop for problems where repetition
    should be terminated at the loop’s middle.
Using the Function
If a programmer now writes the same thing:

#include “Menu.h”

int main()
{
   const string MENU =
      “Please enter:n”
      “ a - to do thisn”
      “ b - to do thatn”
      “ c - to do the othern”
      “--> “;

    char choice = GetValidMenuChoice(MENU, ‘a’, ‘c’);

    // ...
}
Testing
Please enter:
 a - to do this
 b - to do that
 c - to do the other
--> s

** Invalid menu choice ‘s’ entered.

Please enter:
 a - to do this
 b - to do that
 c - to do the other
--> a
...
Summary
C++ provides four different loops for eliciting
 repetitive behavior.
(We’ll see the while loop next time.)
Which one is best to solve a given problem
 depends on the algorithm for that problem.

More Related Content

What's hot (20)

Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
C# Loops
C# LoopsC# Loops
C# Loops
 
C lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareC lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshare
 
Java loops
Java loopsJava loops
Java loops
 
Control statements
Control statementsControl statements
Control statements
 
Conditional Loops Python
Conditional Loops PythonConditional Loops Python
Conditional Loops Python
 
Do...while loop structure
Do...while loop structureDo...while loop structure
Do...while loop structure
 
Java Programming: Loops
Java Programming: LoopsJava Programming: Loops
Java Programming: Loops
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
 
Chap 6(decision making-looping)
Chap 6(decision making-looping)Chap 6(decision making-looping)
Chap 6(decision making-looping)
 
Looping Statement And Flow Chart
 Looping Statement And Flow Chart Looping Statement And Flow Chart
Looping Statement And Flow Chart
 
4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf
 
Loops in java script
Loops in java scriptLoops in java script
Loops in java script
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Menu Driven programs in Java
Menu Driven programs in JavaMenu Driven programs in Java
Menu Driven programs in Java
 
While loop
While loopWhile loop
While loop
 
Types of loops in c language
Types of loops in c languageTypes of loops in c language
Types of loops in c language
 
Looping
LoopingLooping
Looping
 
Programming Fundamentals lecture 8
Programming Fundamentals lecture 8Programming Fundamentals lecture 8
Programming Fundamentals lecture 8
 
Presentation on nesting of loops
Presentation on nesting of loopsPresentation on nesting of loops
Presentation on nesting of loops
 

Viewers also liked (20)

Loops c++
Loops c++Loops c++
Loops c++
 
Dev C++ Code Basic Loop
Dev C++ Code Basic LoopDev C++ Code Basic Loop
Dev C++ Code Basic Loop
 
C++ 11 range-based for loop
C++ 11   range-based for loopC++ 11   range-based for loop
C++ 11 range-based for loop
 
Cpp loop types
Cpp loop typesCpp loop types
Cpp loop types
 
Looping in c++
Looping in c++Looping in c++
Looping in c++
 
Chapter 7 - The Repetition Structure
Chapter 7 - The Repetition StructureChapter 7 - The Repetition Structure
Chapter 7 - The Repetition Structure
 
Flow control in c++
Flow control in c++Flow control in c++
Flow control in c++
 
Flow chart programming
Flow chart programmingFlow chart programming
Flow chart programming
 
Flow of Control
Flow of ControlFlow of Control
Flow of Control
 
45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala
 
Loops
LoopsLoops
Loops
 
Loops
LoopsLoops
Loops
 
Flow of control ppt
Flow of control pptFlow of control ppt
Flow of control ppt
 
Flow charts
Flow chartsFlow charts
Flow charts
 
Control Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, StructuresControl Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, Structures
 
Flow chart
Flow chartFlow chart
Flow chart
 
ppt of flowchart
ppt of flowchartppt of flowchart
ppt of flowchart
 
Flow chart powerpoint presentation slides ppt templates
Flow chart powerpoint presentation slides ppt templatesFlow chart powerpoint presentation slides ppt templates
Flow chart powerpoint presentation slides ppt templates
 
Creating HTML Pages
Creating HTML PagesCreating HTML Pages
Creating HTML Pages
 
Algorithms and Flowcharts
Algorithms and FlowchartsAlgorithms and Flowcharts
Algorithms and Flowcharts
 

Similar to Getting Valid Menu Choices in C

CMIS 102 Hands-On LabWeek 6OverviewThis hands-on lab .docx
CMIS 102 Hands-On LabWeek 6OverviewThis hands-on lab .docxCMIS 102 Hands-On LabWeek 6OverviewThis hands-on lab .docx
CMIS 102 Hands-On LabWeek 6OverviewThis hands-on lab .docxclarebernice
 
Loops_and_FunctionsWeek4_0.ppt
Loops_and_FunctionsWeek4_0.pptLoops_and_FunctionsWeek4_0.ppt
Loops_and_FunctionsWeek4_0.pptKamranAli649587
 
C++ Loops General Discussion of Loops A loop is a.docx
C++ Loops  General Discussion of Loops A loop is a.docxC++ Loops  General Discussion of Loops A loop is a.docx
C++ Loops General Discussion of Loops A loop is a.docxhumphrieskalyn
 
Bottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docxBottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docxAASTHA76
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingNeeru Mittal
 
Introduction to flowchart
Introduction to flowchartIntroduction to flowchart
Introduction to flowchartJordan Delacruz
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.pptsanjay
 
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
 
Java loops for, while and do...while
Java loops   for, while and do...whileJava loops   for, while and do...while
Java loops for, while and do...whileJayfee Ramos
 
import java.util.ArrayList; import java.util.List; import java.u.pdf
import java.util.ArrayList; import java.util.List; import java.u.pdfimport java.util.ArrayList; import java.util.List; import java.u.pdf
import java.util.ArrayList; import java.util.List; import java.u.pdfanupamagarud8
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++msharshitha03s
 
Introductiontoflowchart 110630082600-phpapp01
Introductiontoflowchart 110630082600-phpapp01Introductiontoflowchart 110630082600-phpapp01
Introductiontoflowchart 110630082600-phpapp01VincentAcapen1
 
Menu bars and menus
Menu bars and menusMenu bars and menus
Menu bars and menusmyrajendra
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALPrabhu D
 
Functional Programming in C#
Functional Programming in C#Functional Programming in C#
Functional Programming in C#Giorgio Zoppi
 
Control structures ii
Control structures ii Control structures ii
Control structures ii Ahmad Idrees
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointJavaTpoint.Com
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsDhivyaSubramaniyam
 

Similar to Getting Valid Menu Choices in C (20)

CMIS 102 Hands-On LabWeek 6OverviewThis hands-on lab .docx
CMIS 102 Hands-On LabWeek 6OverviewThis hands-on lab .docxCMIS 102 Hands-On LabWeek 6OverviewThis hands-on lab .docx
CMIS 102 Hands-On LabWeek 6OverviewThis hands-on lab .docx
 
Loops_and_FunctionsWeek4_0.ppt
Loops_and_FunctionsWeek4_0.pptLoops_and_FunctionsWeek4_0.ppt
Loops_and_FunctionsWeek4_0.ppt
 
C++ Loops General Discussion of Loops A loop is a.docx
C++ Loops  General Discussion of Loops A loop is a.docxC++ Loops  General Discussion of Loops A loop is a.docx
C++ Loops General Discussion of Loops A loop is a.docx
 
Bottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docxBottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docx
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
 
Introduction to flowchart
Introduction to flowchartIntroduction to flowchart
Introduction to flowchart
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.ppt
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)
 
Java loops for, while and do...while
Java loops   for, while and do...whileJava loops   for, while and do...while
Java loops for, while and do...while
 
import java.util.ArrayList; import java.util.List; import java.u.pdf
import java.util.ArrayList; import java.util.List; import java.u.pdfimport java.util.ArrayList; import java.util.List; import java.u.pdf
import java.util.ArrayList; import java.util.List; import java.u.pdf
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
03b loops
03b   loops03b   loops
03b loops
 
Introductiontoflowchart 110630082600-phpapp01
Introductiontoflowchart 110630082600-phpapp01Introductiontoflowchart 110630082600-phpapp01
Introductiontoflowchart 110630082600-phpapp01
 
Menu bars and menus
Menu bars and menusMenu bars and menus
Menu bars and menus
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
 
Functional Programming in C#
Functional Programming in C#Functional Programming in C#
Functional Programming in C#
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 

More from Muhammad Uzair Rasheed (20)

Pak Energy conservation
Pak Energy conservation Pak Energy conservation
Pak Energy conservation
 
Pakistan Energy Conservation
Pakistan Energy ConservationPakistan Energy Conservation
Pakistan Energy Conservation
 
Molten Salt Reactor
Molten Salt ReactorMolten Salt Reactor
Molten Salt Reactor
 
Sampling
SamplingSampling
Sampling
 
Zindagi gulzar-hai
Zindagi gulzar-haiZindagi gulzar-hai
Zindagi gulzar-hai
 
Algorithms 1
Algorithms 1Algorithms 1
Algorithms 1
 
Verilog hdl
Verilog hdlVerilog hdl
Verilog hdl
 
Presentation on 2 nd generation telecommunication system
Presentation on 2 nd generation telecommunication systemPresentation on 2 nd generation telecommunication system
Presentation on 2 nd generation telecommunication system
 
Tdm & fdm
Tdm & fdmTdm & fdm
Tdm & fdm
 
Wavelength division multiplexing
Wavelength division multiplexingWavelength division multiplexing
Wavelength division multiplexing
 
Transmission media
Transmission mediaTransmission media
Transmission media
 
Guided media
Guided mediaGuided media
Guided media
 
Phase shift
Phase shiftPhase shift
Phase shift
 
Gsm – global system for mobile communication
Gsm – global system for mobile communicationGsm – global system for mobile communication
Gsm – global system for mobile communication
 
First generation network
First generation networkFirst generation network
First generation network
 
First and second generation communication
First and second generation communicationFirst and second generation communication
First and second generation communication
 
Fdm
FdmFdm
Fdm
 
Channel impairments
Channel impairmentsChannel impairments
Channel impairments
 
Angle modulation
Angle modulationAngle modulation
Angle modulation
 
Analog to-digital conversion
Analog to-digital conversionAnalog to-digital conversion
Analog to-digital conversion
 

Getting Valid Menu Choices in C

  • 1. Muhammad Uzair Rasheed 2009-CPE-03 UCE&T BZU MULTAN •adams@calvin.edu
  • 2. C++ Loop Statements Repetition Revisited
  • 3. Problem Using OCD, design and implement a function that, given a menu, its first valid choice, and its last valid choice, displays that menu, reads a choice from the user, and returns a value guaranteed to be (i) a valid choice from the menu, and (ii) a choice chosen by the user. You may assume that the valid menu choices form a continuous sequence.
  • 4. Preliminary Analysis The tricky part is that the function must return a value that (i) is a valid menu choice; and (ii) was chosen by the user. One way to accomplish both goals is to use a loop that displays the menu, reads the user’s choice, checks its validity, and if it is not valid, gives them another chance...
  • 5. Behavior Our function should receive a menu, its first valid choice and its last valid choice. It should repeatedly display the menu, read the user’s choice, so long as the user’s choice is invalid. It should then return the user’s choice.
  • 6. Objects Description Type Kind Name menu string constant MENU first valid char variable firstChoice choice last valid char variable lastChoice choice user’s choice char variable choice
  • 7. Operations Description Predefined? Library? Name display strings yes iostream << read a char yes iostream >> check validity no built-in <=, && repeat steps yes built-in ? terminate loop yes built-in ? return a char yes built-in return
  • 8. Algorithm 0. Receive MENU, firstChoice, lastChoice. 1. Loop a. Display MENU via cout. b. Read choice from cin. c. If firstChoice <= choice and choice <= lastChoice: terminate repetition. End loop. 2. Return choice.
  • 9. Organization Note that our algorithm terminates the repetition at the bottom of the loop. To code such loops conveniently and readably, C++ provides the do loop.
  • 10. Coding char GetValidMenuChoice(const string MENU, char firstChoice, char lastChoice) { char choice; do { cout << MENU; cin >> choice; } while (choice < firstChoice || choice > lastChoice); return choice; }
  • 11. Discussion The do loop tests its condition at the end of the loop, making it useful for any problem in which the body of the loop must be performed at least once. This function seems general enough to be reuseable by any menu-using program, so it should be stored in a library.
  • 12. Using the Function Once our function is stored in a library, a programmer can write something like this: #include “Menu.h” int main() { const string MENU = “Please enter:n” “ a - to do thisn” “ b - to do thatn” “ c - to do the othern” “--> “; char choice = GetValidMenuChoice(MENU, ‘a’, ‘c’); // ... }
  • 13. Testing Please enter: a - to do this b - to do that c - to do the other --> s Please enter: a - to do this b - to do that c - to do the other --> q Please enter: a - to do this b - to do that c - to do the other --> a ...
  • 14. Note If we wish to display an error message, that changes our algorithm... Such a message should only be displayed if the user enters an invalid value, but should be displayed each time they do so. Our algorithm must be adapted accordingly.
  • 15. Algorithm (revised) 0. Receive MENU, firstChoice, lastChoice. 1. Loop a. Display MENU via cout. b. Read choice from cin. c. If firstChoice <= choice and choice <= lastChoice: terminate repetition. d. Display error message. End loop. 2. Return choice.
  • 16. Organization Our algorithm no longer terminates the repetition at the bottom of the loop. Instead, it terminates repetition in the middle of the loop, suggesting a forever loop. Which loop is best used depends on where execution leaves the loop in one’s algorithm.
  • 17. Coding char GetValidMenuChoice(const string MENU, char firstChoice, char lastChoice) { char choice; for (;;) { cout << MENU; cin >> choice; if (choice >= firstChoice && choice <= lastChoice) break; cerr << “n*** Invalid menu choice: ’“ << choice << “’ entered.n” << endl; } return choice; }
  • 18. Discussion C++ provides a variety of loops: – The for loop for counting problems – The while loop for problems where repetition should be terminated at the loop’s beginning. – The do loop for problems where repetition should be terminated at the loop’s end. – The forever loop for problems where repetition should be terminated at the loop’s middle.
  • 19. Using the Function If a programmer now writes the same thing: #include “Menu.h” int main() { const string MENU = “Please enter:n” “ a - to do thisn” “ b - to do thatn” “ c - to do the othern” “--> “; char choice = GetValidMenuChoice(MENU, ‘a’, ‘c’); // ... }
  • 20. Testing Please enter: a - to do this b - to do that c - to do the other --> s ** Invalid menu choice ‘s’ entered. Please enter: a - to do this b - to do that c - to do the other --> a ...
  • 21. Summary C++ provides four different loops for eliciting repetitive behavior. (We’ll see the while loop next time.) Which one is best to solve a given problem depends on the algorithm for that problem.