Thread: How to include a for loop to keep a running total

  1. #1
    Registered User
    Join Date
    Jul 2012
    Posts
    8

    How to include a for loop to keep a running total

    Hello All. My name is Xinzin, and like many, I would like some assistance. However before we go much further I will describe my very brief history with C++ programming to better inform you how you can help. I am currently taking a summer course for c++ for the past 3 weeks, that said, I only know the extreme basics. cout, cin, basic operators, if statements, if else statements, if else if statements, and just recently the while, do while and for loops. That said, any advanced answers will not help me in the least.

    Anyway, my prof had an assignment to write our own piece of code, which should include the three loops we have learned in class. I decided to create grocery store application in which users can select between regular price, clearance, and special discount items to purchase. It is nearly complete; however I would like to add in a running total using the for loop at the very end, where the menu asks to quit (if you wish to skip ahead, the last default option).

    As for loops are my weakest suit currently, I have tried reading tutorials on how to apply the concepts to a running total, but I don't understand. Any help? Thanks in advance.

    Also, the code runs fine.


    Code:
    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    /*
     * 
     */
    int main(int argc, char** argv) { 
        // Constants for menu choices
     const int Regular = 1,
     Clearance = 2,
     Discount = 3,
     QUIT_CHOICE = 4;
     unsigned short choice; 
      do {
        //Display the menu
        cout<<"Type 1 if you would like to purchase Regular priced items"<<endl;
        cout<<"Type 2 if you would like to purchase Clearance items"<<endl;
        cout<<"Type 3 if you would like to purchase Special Discount items"<<endl;
        cout<<"Type 4 if you would like to quit" <<endl;
        //Declare and input the choice
         cin>>choice;
        // Validate the menu selection.
            while (choice < Regular || choice > QUIT_CHOICE) 
            {
                    cout << "Please enter a valid menu choice: ";
                    cin >> choice;
            }
         //Based upon the choice, proceed to next menu
        switch(choice){
          case 1:{
            // Display the Regular priced menu
            cout<<"Type A if you would like to purchase brand name Cookies "<<endl;
            cout<<"Type B if you would like to purchase brand name Juice "<<endl;
            cout<<"Type C if you would like to purchase brand name Cereal "<<endl;
            cout<<"Type D if you would like to purchase Brand name Crackers "<<endl;
            cout<<"Type E if you would like to purchase Brand name Oatmeal "<<endl;
            //Declare and input choice      
            char choice1;
            cin>>choice1;
           //Based upon the choice, solve the particular problem
         switch(choice1){
          case 'A':{
            // Ask the user how many cookies they want
            cout<<"How many boxes of cookies would you like to buy?"<<endl;
            int Cookies;
            const float Cprice = 5.6, Tax = .0775;
            float Price;
            cin>>Cookies;
            Price = (Cookies * Cprice) + (Cookies * Cprice * Tax);
            cout<<"The price of the cookies are : $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
            break;
                    }
             
          case 'B':{
            // Ask the user how many Juices they want
            cout<<"How many cans of juice would you like to buy?"<<endl;
            int Juice;
            const float Jprice = 5.2, Tax = .0775;
            float Price;
            cin>>Juice;
            Price = (Juice * Jprice) + (Juice * Jprice * Tax);
            cout<<"The price of the Juice is: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
            break;
                    }
            
           case 'C':{
             // Ask the user how many boxes of Cereal they want
             cout<<"How many boxes of cereal would you like to buy?"<<endl;
             int Cereal;
             const float Clprice = 5.2, Tax = .0775;
             float Price;
             cin>>Cereal;
             Price = (Cereal * Clprice) + (Cereal * Clprice * Tax);
             cout<<"The price of the cookies are: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
             break;
                    }
                    
           case 'D':{
             // Ask the user how many boxes of crackers they want
             cout<<"How many boxes of crackers would you like to buy?"<<endl;
             int Crack;
             const float Crackprice = 5.2, Tax = .0775;
             float Price;
             cin>>Crack;
             Price = (Crack * Crackprice) + (Crack * Crackprice * Tax);
             cout<<"The price of the crackers are: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
             break;
                     }
                    
           case 'E':{
             // Ask the user how boxes oatmeal they want
             cout<<"How many boxes of oatmeal would you like to buy?"<<endl;
             int Oats;
             const float Oprice = 5.2, Tax = .0775;
             float Price;
             cin>>Oats;
             Price = (Oats * Oprice) + (Oats * Oprice * Tax);
             cout<<"The price of the oatmeal is: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
             break;
                    }
           default:{
             cout<<"You do not know how to follow instructions, do you?"<<endl;
                   }
           break;
                       }
           break; 
              }
           
          case 2:{
            // Display the Clearance priced menu
            cout<<"Type a if you would like to purchase clearance Cookies "<<endl;
            cout<<"Type b if you would like to purchase clearance Juice "<<endl;
            cout<<"Type c if you would like to purchase clearance Cereal "<<endl;
            cout<<"Type d if you would like to purchase clearance Crackers "<<endl;
            cout<<"Type e if you would like to purchase clearance Oatmeal "<<endl;
            //Declare and input choice      
            char choice2;
            cin>>choice2;
           //Based upon the choice, solve the particular problem
         switch(choice2){
            case 'a':{
                // Ask the user how many cookies they want
                cout<<"How many boxes of cookies would you like to buy?"<<endl;
                int ClearCookies;
                const float OCprice =5.6, ClCprice = 4.0, Tax = .0775;
                float Oprice, Price, Diff, Savings; // Diff = difference in price, Savings = % you saved
                cin>>ClearCookies;
                Price = (ClearCookies * ClCprice) + (ClearCookies * ClCprice * Tax);
                Oprice =(ClearCookies * OCprice) + (ClearCookies * OCprice * Tax);
                Diff = Oprice - Price;
                Savings = 100 - (Price / Oprice) * 100 ;
                cout<<"The price of the cookies are : $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
                cout<<"You saved $ " <<fixed<<setprecision(2)<<Diff<<" "<<endl;
                cout<<"Thats a savings of " <<fixed<<setprecision(0)<<Savings<<" %"<<endl;
                break;
                       }
                    
             case 'b':{
                // Ask the user how many Juices they want
                cout<<"How many cans of juice would you like to buy?"<<endl;
                int ClJuice;
                const float OJJprice = 5.2, ClJprice = 3.6, Tax = .0775;
                float Price, OJYPrice, Diff, Sav;
                cin>>ClJuice;
                Price = (ClJuice * ClJprice) + (ClJuice * ClJprice * Tax);
                OJYPrice = (ClJuice * OJJprice) + (ClJuice * OJJprice * Tax);
                Diff = OJYPrice - Price;
                Sav = 100 - (Price / OJYPrice) * 100;
                cout<<"The price of the Juice is: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
                cout<<"You saved $ " <<fixed<<setprecision(2)<<Diff<<" "<<endl;
                cout<<"Thats a savings of " <<fixed<<setprecision(0)<<Sav<<" %"<<endl;
                break;
                       }
                    
             case 'c':{
                // Ask the user how many boxes of Cereal they want
                cout<<"How many boxes of cereal would you like to buy?"<<endl;
                int ClCereal ;
                const float OClprice = 5.2, ClCrprice = 2, Tax = .0775;
                float Price, Ocer, Diff, Sav; // Ocer=OriginalCeral Price
                cin>>ClCereal;
                Price = (ClCereal * ClCrprice) + (ClCereal * ClCrprice * Tax);
                Ocer = (ClCereal * Ocer) + (ClCereal * Ocer * Tax);
                Diff = Ocer - Price;
                Sav = 100 - (Price/ Ocer) * 100;
                cout<<"The price of the cookies are: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
                 cout<<"You saved $ " <<fixed<<setprecision(2)<<Diff<<" "<<endl;
                cout<<"Thats a savings of " <<fixed<<setprecision(0)<<Sav<<" %"<<endl;
                break;
                       }
                    
             case 'd':{
                // Ask the user how many boxes of crackers they want
                cout<<"How many boxes of crackers would you like to buy?"<<endl;
                int ClCrack;
                const float OCrackprice = 5.2, ClCrackprice = 1.9, Tax = .0775;
                float Ocrack, Price, Diff, Sav;
                cin>>ClCrack;
                Price = (ClCrack * ClCrackprice) + (ClCrack * ClCrackprice * Tax);
                Ocrack = (ClCrack * OCrackprice) + (ClCrack * OCrackprice * Tax);
                Diff = Ocrack - Price;
                Sav = 100 - (Price/Ocrack) * 100;
                cout<<"The price of the crackers are: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
                cout<<"You saved $ " <<fixed<<setprecision(2)<<Diff<<" "<<endl;
                cout<<"Thats a savings of " <<fixed<<setprecision(0)<<Sav<<" %"<<endl;
                break;
                        }
                    
             case 'e':{
                // Ask the user how boxes oatmeal they want
                cout<<"How many boxes of oatmeal would you like to buy?"<<endl;
                int ClOats;
                const float Oprice = 5.2, ClOprice = 2.3, Tax = .0775;
                float Price, Ooats, Diff, Sav;
                cin>>ClOats;
                Price = (ClOats * ClOprice) + (ClOats * ClOprice * Tax);
                Ooats= (ClOats * Oprice) + (ClOats * Oprice * Tax);
                Diff = Ooats - Price;
                Sav = 100 - (Price / Ooats) * 100;
                cout<<"The price of the oatmeal is: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
                cout<<"You saved $ " <<fixed<<setprecision(2)<<Diff<<" "<<endl;
                cout<<"Thats a savings of " <<fixed<<setprecision(0)<<Sav<<" %"<<endl;
                break;
                        }
            default:{
                cout<<"You do not know how to follow instructions, do you?"<<endl;
                    }
            break;
                  }
                break;
            }
          case 3:{
                // Display another menu
                cout<<"Press Q if you would like to buy Cheese"<<endl;
                cout<<"Press W if you would like to buy Milk"<<endl;
                cout<<"Press E if you would like to buy Candy"<<endl;
                cout<<"Press R if you would like to buy Tea"<<endl;
                cout<<"Press T if you would like to buy Water"<<endl;
                //Declare and input the choice
                char choice3;
                cin>>choice3;
                //Based upon the choice, proceed to next menu
            switch(choice3){
              case 'Q':{
                // Ask the user how much cheese
                cout<<"How much cheese would you like to buy?"<<endl;
                int Cheese;
                const float Cheeseprice = 3.99, Tax = .0775;
                float Price;
                cin>>Cheese;
                    if (Cheese ==1) {
                            Price = (Cheese * Cheeseprice) + (Cheese * Cheeseprice * Tax) -1;
                            cout<<"The price of the cheese after discount is $"<<fixed<<setprecision(2)<<Price<<" "<<endl;
                                    }
                    else {
                            Price = (Cheese * Cheeseprice) + (Cheese * Cheeseprice * Tax);
                            cout<<"The price of the cheese is : $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
                            }
                break;
                        }
            
                case 'W':{
                    // Ask the user how much Milk they want
                    cout<<"How many gallons of Milk would you like to buy?"<<endl;
                    int Milk;
                    const float Mprice = 3.39, Tax = .0775;
                    float Price;
                    cin>>Milk;
                    if (Milk >= 5 || Milk <= 10) {
                            Price = (Milk * Mprice);
                            cout<<"The price of the milk after discount is: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
                                                  }
                    else {
                            Price = (Milk * Mprice) + (Milk * Mprice * Tax);
                            cout<<"The price of the milk is: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
                         }
                    break;
                         }
            
                case 'E':{
                     // Ask the user how many boxes of Candy they want
                    cout<<"How many boxes of Candy would you like to buy?"<<endl;
                    int Candy;
                    const float CanPrice = 1.2, Tax = .0775;
                    float Price;
                    cin>>Candy;
                    if (Candy > 9) {
                            Price = ((Candy * CanPrice) + (Candy * CanPrice * Tax)) - ((CanPrice * Tax ) + CanPrice) ;
                            cout<<"The price of the candy after discount is: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
                                    }
                    else {
                            Price = (Candy * CanPrice) + (Candy * CanPrice * Tax)  ;
                            cout<<"The price of the candy is: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
                         }
                    break;
                            }
            
                case 'R':{
                    // Ask the user how many tea packets they want
                    cout<<"How many packets of tea would you like to buy?"<<endl;
                    int Tea;
                    const float Tprice = 2.89, Tax = .0775;
                    float Price;
                    cin>>Tea;
                    if (Tea <4) {
                            Price = (Tea * Tprice) + (Tea * Tprice * Tax) * .50;
                            cout<<"The price of the Tea after discount is: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
                                }
                    else{
                            Price = (Tea * Tprice) + (Tea * Tprice * Tax);
                            cout<<"The price of the Tea is: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
                        }
                break;
                          }
            
                case 'T':{
                    // Ask the user how gallons of water  they want
                    cout<<"How many gallons would you like to buy?"<<endl;
                    int Wat;
                    const float Wprice = 1.0, Tax = .0775;
                    float Price;
                    cin>>Wat;
                    if (Wat < 3, Wat > 1) 
                            {
                            Price = (Wat * Wprice) + (Wat * Wprice * Tax) * .05;
                            cout<<"The price of the Water after discount is: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
                            }
                    else if (Wat < 4 , Wat > 2) 
                            {
                            Price = (Wat * Wprice) + (Wat * Wprice * Tax) * .06;
                            cout<<"The price of the Water after discount is: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
                            } 
                    else if (Wat >3) 
                    {
                            Price = (Wat * Wprice) + (Wat * Wprice * Tax) * .07;
                            cout<<"The price of the Water after discount is: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
                    }
                    else {
                            Price = (Wat * Wprice) + (Wat * Wprice * Tax);
                            cout<<"The price of the oatmeal is: $ " <<fixed<<setprecision(2)<<Price<<" "<<endl;
                         }
                break;
                       }
            default:{
                cout<<"You do not know how to follow instructions, do you?"<<endl;
                    }
            break;    
                      }    
            break;
            }
            default:{
                cout<<"Why don't you want to shop anymore?"<<endl;
                    }
               }
         } while (choice!= QUIT_CHOICE); 
         return 0;
     }

  2. #2
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    A running total of what?

    broadly speaking for loops are used when you want to something for every element in something or for every number in a set. What range of values do you want to create a running total of? You probably need to store those values to loop over them.

    Normally you'd want to keep a running total in the loop creating the values, but I realize that the point here is to use a for loop, not to have optimal code.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  3. #3
    Registered User
    Join Date
    Jul 2012
    Posts
    87
    You need to keep track of the total with a variable. In the e.g. I have called it total_so_far, that's all. Here's the gist:

    Code:
    #include <iostream>
    #include <iomanip>
    
    using namespace std;
    
    int main()
    {
      int input = -99;
      double total_so_far = 0;
      double tax = 1.05;
    
      string instructions = "Welcome to Buy Stuff online \n \
      To buy:\n \
      a sandwich ($1.29), press 1, then Enter\n \
      box of sushi($3.15), press 2, then Enter\n \
      an apple($0.99), press 3, then Enter\n \
      To quit shopping, press -1, then Enter) and to\
     pull up the menu, presss 0, then Enter";
      cout << instructions << endl;
      
      do
      {
        cout << "Choose an option, then press Enter" << endl;
        cin >> input;
       
        if ( input == 1 )
          total_so_far += 1.29;//simplified notation for: total_so_far = total_so_far + 1.29
        if ( input == 2 )
          total_so_far += 3.15;
        if ( input == 3 )
           total_so_far += 0.99;
        if ( input == 0 )
            cout << instructions << endl;
      }
      while ( input != -1 );
    
      double payment = total_so_far * tax;
      cout << "Please pay $" << setprecision(3) << payment << endl;
      cout << "Thx for shopping, later!" << endl;
      return 0;
    }
    Last edited by monkey_c_monkey; 07-13-2012 at 09:34 PM.

  4. #4
    Registered User
    Join Date
    Jul 2012
    Posts
    8
    I would like to keep a running total of all the purchases made as the loop returns the user the main menu before they quit. As for range, I don't have anything specific. I wanted to total to increase until the user was tired and quit, in which the quit option would display the final total. To store values, how exactly? using the "+=" operator? Wouldn't I need to use the for loop during the storing of values?

    Edit: So essentially I need to add an if statement to every option?
    Also, does this mean using the for loop is an impossible task?
    Last edited by Xinzin; 07-13-2012 at 09:23 PM.

  5. #5
    Registered User
    Join Date
    Jul 2012
    Posts
    87
    You don't have to use if, you can stick with switch statements. As long as you have some loop and the input is not to quit, then the total will accumulate as long as you have a variable that keeps adding to itself (i.e. total_so_far = total_so_far + price_of_this_item). So each item would have this total_so_far += price_of_this_item. A switch statement can act as a header to be cleaner I guess, but you could just as easily use an if ( case == 'a' ) do this, if (case =='b') do this etc.

    I don't get what you mean using a for loop is an impossible task?
    Last edited by monkey_c_monkey; 07-13-2012 at 09:34 PM.

  6. #6
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    You already have a loop for when your buying stuff.

    If you use std::vector, then you can add values to it using the push_back() method. Something like this:
    Code:
    #include <vector>
    
    std::vector<int> purchases;
    
    while(...){
       ...
      if (purchase_something)
         purchases.push_back(value);
       ...
    }
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  7. #7
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Quote Originally Posted by monkey_c_monkey View Post
    You don't have to use if, you can stick with switch statements. As long as you have some loop and the input is not to quit, then the total will accumulate as long as you have a variable that keeps adding to itself (i.e. total_so_far = total_so_far + price_of_this_item). So each item would have this total_so_far += price_of_this_item. A switch statement can act as a header to be cleaner I guess, but you could just as easily use an if ( case == 'a' ) do this, if (case =='b') do this etc.

    I don't get what you mean using a for loop is an impossible task?
    This is exactly how It should be done, but then there's no for loop. Which defeats the point of doing it in the first place.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  8. #8
    Registered User
    Join Date
    Jul 2012
    Posts
    8
    Quote Originally Posted by King Mir View Post
    You already have a loop for when your buying stuff.

    If you use std::vector, then you can add values to it using the push_back() method. Something like this:
    Code:
    #include <vector>
    
    std::vector<int> purchases;
    
    while(...){
       ...
      if (purchase_something)
         purchases.push_back(value);
       ...
    }
    My prof has not taught the class the vector or pushback method. Besides being suspicious I have no idea how manipulate the code if I used them. Sorry =/

  9. #9
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Then you cannot use a for loop to compute the running total. Well, you could use another container instead, but that's not easier.

    monkey_c_monkey's code works of course, and computes the running total, but it does not use a for loop.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  10. #10
    Registered User
    Join Date
    Jul 2012
    Posts
    8
    I see, that answers my question. So maybe another? When would you use the for loop? I understand concepts books and tutorial say, but they are sticking for some reason. Would you be gracious enough to provide real examples when one would use the for loop?

  11. #11
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Pretty much any time you need a loop that's not limited by IO/user input. Like to do something X times, maybe with a small difference dependant on the index in each iteration.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  12. #12
    Registered User
    Join Date
    Jul 2012
    Posts
    87
    Gist is: for loops you think of when you are counting something vs while loops when you need to do a task until some condition is false. So if it helps you can say to yourself: Do these tasks for as long as I need to vs do these tasks while some condition holds. The beauty of a for loop is that it is a step above a while loop so to speak.

    In dissecting a for loop, you three segments:
    Code:
    //FOR LOOP: for ( initalizer(s); condition(s); operation(s) )
    { 
     BODY;
     } 
    vs  
    WHILE LOOP: 
    initializer(s) 
    while ( condition(s) )
    { 
     BODY;
     operation(s);
     }
    Do you see how they are essentially the same, the beauty of a for-loop is the three segments are contained within the for loop header, whereas while loops is in three places. They both do the same thing, it's just a matter of taste and especially when you'll going to be dealing with let's say 2D or higher arrays, using double for loops just looks cleaner w/o having the three segments all over the place. The only difference b/t while and do-while loops btw, is that while loop is pre-condition (if evaluation/condition is true, then it enters the body of while loop) vs do-while is pre-condition (condtion is evaluated after body is executed).

    The more algorithms you write, the more you'll become comfortable in naturally deciding to choose one loop over another.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. whileloop/running total problem
    By psynt555 in forum C Programming
    Replies: 2
    Last Post: 01-22-2012, 09:36 AM
  2. loop is running twice
    By Nikitaatwork in forum C Programming
    Replies: 4
    Last Post: 11-08-2011, 06:42 PM
  3. Can't get loop to keep running
    By mytrademark in forum C Programming
    Replies: 2
    Last Post: 11-01-2011, 06:08 PM
  4. Total C newbie -- PLEASE HELP with writing a LOOP, asap!!!!
    By Laila Sawyer in forum C Programming
    Replies: 19
    Last Post: 07-26-2011, 06:18 AM
  5. Replies: 3
    Last Post: 06-12-2011, 10:17 AM

Tags for this Thread