Add Up Numbers: Get to 21 or Stop at 0

  • Context:
  • Thread starter Thread starter MMOne
  • Start date Start date
  • Tags Tags
    Numbers
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 2K views
MMOne
Messages
3
Reaction score
0
Ask the user for a number between 1 and 11; stop asking when the user enters 0 OR when the total goes over 21. Display the total on the screen. For example:

#include<iostream>
#include<cmath>
using namespace std;
int main(){

int num, total;

count << "Enter a number between 1 and 11 (0 to stop): ";
cin >> num;
count << num << endl;

while((num > 0)&&(num < 12)){
count << num << endl;

total = total + num;
while ((num == 0) || (total > 21)){
count << "Your total was " << total << endl;
count << "Thanks for playing!" << endl;
}
}
return 0;
}

When I compile it will not provide the messages at the end. Not sure how to do this my code might just be sloppy. Any help would be appreciated.
 
Physics news on Phys.org
This is how I'd code it. I didn't compile and run it, though.

Code:
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int num;
    int total = 0;
    int quit = 0;

    while (!quit) {
        cout << "Enter a number between 1 and 11 or 0 to quit." << endl;
        cin >> num;

        if (num == 0)
          quit = 1;
        else if (num < 1 || num > 11)
                cout << "Invalid number." << endl;
        else {
             total = total + num;
             if (total > 21)
               quit = 1;
        }
    }

    cout << "Your total was " << total << endl;
}