473,811 Members | 3,811 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need to add a loop to exit or repeat program

5 New Member
Hi all,

I have written a C ++ program and now need to add a way to make it exit on command, or start over from the beginning. I have very little programming knowledge; Here is my code:
Thanks in advance for any help.

Expand|Select|Wrap|Line Numbers
  1. ///////////////////////////////////////////////////////////////////////////////////////////////////                                                                                      //                                                                
  2. //Program Discription, Show name and number of Stock for purchase                                //
  3. //Calculate 100 shares by 63.25 and add .02 cent commission per share.                           //
  4. //Calculate Commission at 39.95 if Subtotal at or over 39.95                                     //
  5. ///////////////////////////////////////////////////////////////////////////////////////////////////                                        
  6. //Version Control:                                                                               // 
  7. //Beta ver set up main Algorythm and function,initalize variables                                //
  8. //perform calculations:                                                                          //
  9. //a=1-100 shares, b=cost per share, c=Subtotal(a*b),d=2cent commission rate                      //
  10. //e=Commission rate* number of shares,f=39.95,g=grandTotal(Commission rate Due + Subtotal Sales) //
  11. //Version 2:                                                                                     //
  12. //1/27/07/                                                                                       //
  13. //Modify code to request and accept user input for number of shares wanted, price of each share  //
  14. //and Grand Total of final Transaction. Add user loop-back structer for new data.                //
  15. ///////////////////////////////////////////////////////////////////////////////////////////////////
  16. #include <iostream>
  17. #include <math.h>
  18. #include <iomanip>
  19. using namespace std;
  20. int main()
  21. {
  22.  
  23.     int a=0;
  24.     double b=0,c=0,d=0.02,e=0,f=0;
  25.     cout<<fixed<<showpoint;
  26.  
  27.           cout<<"\n Market Shares For Sale! \n"  <<endl;
  28.  
  29.  
  30.         // user enters number of shares to buy
  31.  
  32.         cout<<"\t Cocoa-Cola Stock. Select the number of shares  (1-1000):$  \n"<<flush;
  33.                  cin>>a;
  34.                    if(a<1 ||a>1000){
  35.                       cout<<"\t Not a valid Entry. Must be 1 to 1000.\n"<<flush<<endl;
  36.                       }
  37.             cout<<endl;
  38.         //user enters cost per share
  39.             cout<<"\t What is the Price Per Share:$  \n"<<flush;
  40.                   cin>>b;
  41.                   cout<<endl;
  42.                   cout<<endl;
  43.                //Find amount of Commission due
  44.  
  45.                  cout<<"\t This is the amount of Commission Due at 2cent a share:$  \n"<<(a*d)<<endl;
  46.                    e=a*d;
  47.                   if (e>39.95){
  48.                         cout<<"\t Commission plus Sub-Total=Grand Total.Please Pay this Amount:$ \n"<<(c+e)<<f;
  49.                         }   
  50.                   else if(e<39.95){        //calculate the price of shares by the number of shares 
  51.                      cout<<"\t This is the Total of your purchase=:  \n"<<(a*b)<<c<<endl;
  52.                   }
  53.  
  54.  
  55. return 0;
  56.  
  57. }
Jan 28 '07 #1
8 29131
Banfa
9,065 Recognized Expert Moderator Expert
call/look up the function

void exit(int);
Jan 29 '07 #2
Nasutperaah
5 New Member
Hi Benfa,


First thanks for the reply.
After some looking/research I'm still not sure this is the answer to my problem.

I found this example and think I can modify it to suit my needs.

int main()

{

char selection = 'y';



while (tolower(select ion) == 'y') // loop while selection is 'y'

{

cout << "Do you want to continue (y/n):\n";

cin >> selection;

if (cin.fail() || !(tolower(selec tion) == 'y' || tolower(selecti on) == 'n'))

{

cout << "You entered an invalid input, program will restart.\n";

selection = 'y'; //make sure we continue the loop

continue; //jump back to the start of the while loop

}

cin.clear(); //clear the error flag

cin.ignore(100, '\n');// toss out the corrupted input buffer, up to 100 chars



if (tolower(select ion) == 'n')

return 0;

cout << "here we add some code to do some stuff\n";



}


What I still need to know is: do I place the modification at the end of my code or before my code? Or does it even matter?

Thank you so much for the help. I needed a wise pair of eyes!
Jan 30 '07 #3
Nasutperaah
5 New Member
Hi Benfa,


First thanks for the reply.
After some looking/research I'm still not sure this is the answer to my problem.

I found this example and think I can modify it to suit my needs.

int main()

{

char selection = 'y';



while (tolower(select ion) == 'y') // loop while selection is 'y'

{

cout << "Do you want to continue (y/n):\n";

cin >> selection;

if (cin.fail() || !(tolower(selec tion) == 'y' || tolower(selecti on) == 'n'))

{

cout << "You entered an invalid input, program will restart.\n";

selection = 'y'; //make sure we continue the loop

continue; //jump back to the start of the while loop

}

cin.clear(); //clear the error flag

cin.ignore(100, '\n');// toss out the corrupted input buffer, up to 100 chars



if (tolower(select ion) == 'n')

return 0;

cout << "here we add some code to do some stuff\n";



}


What I still need to know is: do I place the modification at the end of my code or before my code? Or does it even matter?

Thank you so much for the help. I needed a wise pair of eyes!



Benfa,

my program runs through the code once and when y(for Yes) is entered the program will repeat from the beginning, but only once more. How do I get it to
repeat until the condition q(for Quit) is met?
Feb 2 '07 #4
RedSon
5,000 Recognized Expert Expert
Benfa,

my program runs through the code once and when y(for Yes) is entered the program will repeat from the beginning, but only once more. How do I get it to
repeat until the condition q(for Quit) is met?
Look closely at the flow of the program after it enters into the loop. Why would entering in 'y' then run your program one more time and quit? What is your code doing after it takes the input from the user?
Feb 2 '07 #5
Nasutperaah
5 New Member
Hi Red S.
I am not sure what you mean. If I pick up the block of code and place it in a second if statement it will run another time. What I want to know is there a way to keep the loop going without making some many blocks of the same code?
Feb 3 '07 #6
Banfa
9,065 Recognized Expert Moderator Expert
I have to say I see no problem with your last posted code, it requests input, makes sure that the input is valid then if the input is 'n' it returns else it runs the following code block.
Feb 3 '07 #7
RedSon
5,000 Recognized Expert Expert
Hi Red S.
I am not sure what you mean. If I pick up the block of code and place it in a second if statement it will run another time. What I want to know is there a way to keep the loop going without making some many blocks of the same code?
I apologize, I thought you were trying to get it to stop after you asked the user for input. They way you have it now if the user says no the program will run one more time then the exit condition for the while loop is met and the code exits. I see now that you want it to continue indefinetly until the user says something. So you want your code to look like this.
Expand|Select|Wrap|Line Numbers
  1. bool done = false;
  2. while (!done)
  3. {
  4.  
  5. ...your code goes here...
  6.  
  7.   cout << "Do you want to quit?";
  8.   cin >> selection;
  9.  
  10.   if (selection == yes)
  11.   {
  12.      done = true;
  13.   }
  14. }
  15.  
Feb 5 '07 #8
Nasutperaah
5 New Member
Thank you for getting back to me and seeing what the real problem was.
I was able to fix the problem with this.



I apologize, I thought you were trying to get it to stop after you asked the user for input. They way you have it now if the user says no the program will run one more time then the exit condition for the while loop is met and the code exits. I see now that you want it to continue indefinetly until the user says something. So you want your code to look like this.
Expand|Select|Wrap|Line Numbers
  1. bool done = false;
  2. while (!done)
  3. {
  4.  
  5. ...your code goes here...
  6.  
  7.   cout << "Do you want to quit?";
  8.   cin >> selection;
  9.  
  10.   if (selection == yes)
  11.   {
  12.      done = true;
  13.   }
  14. }
  15.  
Feb 8 '07 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

43
5608
by: Gremlin | last post by:
If you are not familiar with the halting problem, I will not go into it in detail but it states that it is impossible to write a program that can tell if a loop is infinite or not. This is a fallacy built on the assumption of mythical infinite all powerfull machines. In reality we deal with finite machines that are capable of two states in a loop, they either terminate, or repeat themselves. In the mythical halting problem scenario...
8
1692
by: Microsoft | last post by:
I have the following loop the length contains somewhere around 1000+ items: For elemIndex = 0 To len - 1 elem = CType(doc.all.item(elemIndex), mshtml.IHTMLElement) If elem.tagName = "A" Then If elem.innerText = "1." Then elem.click() End If End If Next elemIndex
4
2231
by: Arnold | last post by:
Hi there, Here's the situation--there is a text field in a form in which students will key in data. On the keypress event, I'd like for different sounds to be played for each character typed, either randomly or in a loop (I have a number of small, cool, computer-like sounds). I can get one sound to play for the keypress event, but don't know how to play multiple sounds. Here's the codes for playing one sound...
12
2821
by: asif929 | last post by:
I am trying to write a program which creates four triangles. The program begins with prompting a user " Enter the size of triangles", number from 1 to N is the size of four triangles For Example if we enter 4, the size of four triangles are 4 rows. In addition, I am also writing a program which i started and failed in giving the right size of traingles. I will appreciate if somebody can help.
1
5693
by: peterggmss | last post by:
This is a slot machine game, 2 forms. One is the actual game (frmMachine) and the other is in the background and randomizes the images shown on frmMachine. I need to make frmMachine wait for frmRandom, i tried it with the Sleep API and a Do/Until Loop and neither worked, could you please help me, I have my code below. frmMachine 'Slot Machine, (c) 2006 Peter Browne, GPL Licensed ' 'Peter Browne 'Sheridan Corporate Centre '2155 Leanne...
0
7118
by: south622 | last post by:
I'm taking a beginning Java course and I'm stuck in week eight of a nine week course. If anyone could help me I would greatly appreciate it. This assignment was due yesterday and each day I go past the due date 10% of the grade is taken off. I think I'm coming down with the flu and my brain is just not processing this assignment. Here is the assignment: Modify the Inventory program by adding a button to the GUI that allows the user to move...
14
3227
namcintosh
by: namcintosh | last post by:
Hello, everyone. Well, let me cut to the chase and explain my problem. I am trying to devise a menu plan that uses the if/else if and the while loop. The program calculates the user's weight on a given planet. It first asks for the user's weight, asks them for a choice. If they choose choices 1 though 9, the user's weight will be calculated on whatever choice they picked (for example, if the user inputs 150 as their weight and choose...
18
2107
by: Vijaykumar Dave | last post by:
I have a program for base X power N as under. The problem is that when the range specified in loop is given it works well, but when any character is pressed, it goes to infinite loop. Second problem is it works fine for smaller value of X or N but not for higher say base 15 power 20. How can I get true value displayed with such higher base or power.? Can any one help me to correct this program putting proper loop and for high value...
3
4490
by: 100grand | last post by:
Modify the Inventory Program to use a GUI. The GUI should display the information one product at a time, including the item number, the name of the product, the number of units in stock, the price of each unit, and the value of the inventory of that product. In addition, the GUI should display the value of the entire inventory, the additional attribute, and the restocking fee. Here is my Inventory program from 1 to 3: package...
0
9604
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10127
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9201
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7665
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5552
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4336
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3863
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.