So I am working on a switch statement but I am not quite sure if I am doing this right. This is my first tiny program using C++ (visual studio 2010) and I am not sure that I am using the switch statement quite right. What I am trying to do is have a person input numbers. I have a counter set up to count the number of inputs as well as I have a running total to output at the sum of all numbers inputted.
while (additional_input > 0)
{
cout << "Enter additional number, use 0 to exit: ";
cin >> additional_input ;
count ++; //increment the counter
//Do the addition
sum += additional_input; //sum up all inputs
} //end of the while statement
switch (sum){ //this is where I get into trouble
case 0-99: cout << "\n\n"; //original question, can I do this?
cout << "Thank you. The sum of your numbers is........: " << sum << endl ;
cout << "The total number of inputs read..............: " << count << endl;
cout << "The sum of your numbers is less than 100" << endl;
return 0;
break;
case 100: cout << "\n\n"; //and so on
So my question is whether or not this is possible. Can I use this for a case?
Standard C++ does not allow case ranges, in your code 0-99 will just end up being evaluated as 0 minus 99 which means what you have is essentially:
case -99:
one alternative is to use an if statement instead so:
case 0-99
would become:
if( sum >= 0 && sum <= 99 )
{
}
Some compilers including gcc offer case ranges as an extension but this would make your code non-standard and not portable and since you are using Visual Studio probably does not apply.
I actually figured this out. It is better to set a case based on the sum. Since I had 3 cases that I was working with, I just made it select the case based on the the total that I had previously gotten. Below is my code:
while (additional_input > 0)
{
cout << "Enter additional number, use 0 to exit: ";
cin >> additional_input ;
count ++; //increment counter
//Do the addition
sum += additional_input; //sum up all inputs
} //end of the while statement
if (sum < 100){ //set condition for option 1
option =1;}
else if (sum == 100){//set condition for option 2
option =2;}
else if (sum > 100)
{option = 3; //last resort option 3
}
switch (option)
{
case 1: cout << "\n\n";//new line
cout << "Thank you. The sum of your numbers is........: " << sum << endl ;
cout << "The total number of inputs read..............: " << count << endl;
cout << "The sum of your numbers is less than 100" << endl;
break;
case 2: cout << "\n\n";//new line
Works like a charm.
Related
I've met some problem during programming. I want to write a program to differentiate even numbers, odd numbers, zero values and negative numbers by using while and for loop.
1st question :
However, when I try to run my program, the last number I've entered will not be counted. I know it occur because of my o++ put at the top of the if condition, how should I solve my problem?
2nd question :
For the for loop parts, actually it may ignored those negative values. How should I solve it to let the negative numbers also count in loop ? May I changed the num>0 to num < 100000 to let the for loop works?
#include<iostream>
using namespace std;
#include<iostream>
using namespace std;
int main ()
{
int num ,numbers = 1 ;
char answer = 'Y' ;
int o=0, e=0, z=0 ,n=0 ;
// o for odd numbers, e for even numbers, z for zero values, n for negative numbers
cout << "Enter number" << numbers << ": " << endl ;
cin >> num ;
for ( num = num ; num >0; num++)
while (answer == 'y' || answer == 'Y')
{
if (num % 2 == 0 && num > 0)
{
e++ ;
cout<< "The number of even numbers is :" << e << endl;
numbers ++ ;
cout<<"Please enter number" << numbers << endl ;
cin >> num ;
cout<<"If you wish to continue, Please enter y or Y to continue this program : "<< endl ;
cin>> answer ;
}
else if (num % 2 == 1 && num > 0)
{
o++;
cout<< "The number of odd numbers is :" << o << endl;
numbers ++ ;
cout<<"Please enter number" << numbers << endl ;
cin >> num;
cout<<"If you wish to continue, Please enter y or Y to continue this program : "<< endl ;
cin>> answer ;
}
else if (num == 0)
{
z ++;
cout<< "The total of 0 is :" << z << endl;
numbers ++ ;
cout<<"Please enter number" << numbers << endl ;
cin >> num;
cout<<"If you wish to continue, Please enter y or Y to continue this program : "<< endl ;
cin>> answer ;
}
}
cout << "The total even numbers is :" << e << endl;
cout << "The total odd numbers is :" << o << endl ;
cout << "The total negative numbers is :" << n << endl ;
cout << "The total zero number is:" << z << endl;
return 0;
}
This line, in main() is really puzzling:
// ...
for ( num = num ; num >0; num++)
while (answer == 'y' || answer == 'Y')
The for(;;) statement is your main loop. The while statement will be executed as long as num is positive.
Let's look at this for() statement in detail:
for (num = num; // num = num ??? this statement does nothing.
num > 0; // the while statement (and the contents of the whule() loop block)
// will only execute if num is > 0.
++num) // if num was > 0 then this loop will run until num overflows...
Removing the for(;;) statement will make your program run a lot better.
Your o++ has nothing do with it.
(Perhaps you have been so convinced about that being the problem that you didn't think of looking elsewhere. It happens to everyone.)
The problem is that your sequence is this:
Check the most recently entered number and print the result
Ask the user for a number, but don't do anything with it
Ask the user whether they want to continue
If they want to continue, repeat from item 1
If they don't, stop counting
And since you stop counting if the user doesn't want to continue, the last number seems to have disappeared.
Fixing it left as an exercise.
(Think more carefully about which order you need to do things in.)
Handling negative numbers requires you to write some code to do that - you handle two cases of positive numbers, and one for zero, but you must have forgotten about the negatives.
Fixing this also left as an exercise.
I am writing a program to very fundamentally simulate a black jack game using rand() % 11. We have to tell the players their running total as well as asking if they want another card (hit). My first problem is getting multiple random numbers and my second problem is not being able to add the two random numbers together. Strings are not allowed. Here's the block of code that I think is causing there's errors. I am very new to c++. Do I need to have multiple variables with the rand() %10 +1 to add them? I know that the add + add won't work but I can't figure out an alternative.
int add = rand() % 10 + 1;
bool hit = false;
int i = 0;
do {
cout << "Players 1 running total is " << add;
i++;
cout << " \n ";
cout << "Would you like another number? (0-yes or 1-no) ";
cin >> hit;
if ( hit == 0 ) {
cout << " You got an " << add << " \n ";
cout << "You're running total is " << add + add;
}
} while ( hit == false );
I assume this is an assignment given by an educator, otherwise, you shouldn't be using rand() at all (I don't blame you, I blame the instructor for not keeping up with the language.)
You must call rand() again to get a new number and use another variable to store the total:
Sidenote:
You should really declare your variables as close to first use as possible instead of the top of the program.
Also, The variable i isn't being used in this context so I removed it.
srand(time(0)); //Should be nullptr, but instructor probably doesn't know that.
int total = 0;
bool hit = false;
do {
int add = rand() % 10 + 1;
total += add;
cout << "\nYou got an " << add << " \n ";
cout << "\nPlayer 1 running total is " << total;
cout << "\nWould you like another number? (0-yes or 1-no) ";
cin >> hit;
} while (hit == false);
cout << "Player 1 final total is: " << total << endl;
#include <iostream>
#include <iomanip>
using namespace std;
const int N = 20;
int main ()
{
//Declare variables
int counter; //loop control variable
int number; //variable to store the new number
int zeros = 0; //Step 1
int odds = 0; //Step 1
int evens = 0; //Step 1
int positives = 0;
int negatives = 0;
// Display Program Intro telling what the program does.
cout << "********************************************************"
<< "\n* This is a program that counts integers you enter as *"
<< "\n* even, odd or zero and positve or negative *"
<< "\n* It classifies 20 numbers or use 99999 to exit early *"
<< "\n********************************************************"
<< endl;
// Ask for 20 integers with 99999 as early exit
cout << "\n\nPlease enter " << N << " integers, "
<< "positive, negative, or zeros."
<< "\n\t\t or enter number 99999 to exit early. \n\n"
<< endl; //Step 2
cout << "The numbers you entered are:" << endl;
// Loop that classifies the numbers entered.
for (counter = 1; counter <= N; counter++) //Step 3
{
// Enter number and mirror it backed on a tabbed line.
cin >> number; //Step 3a
cout << number << endl; //Step 3b
// Early exit condition: 99999
if(number = 99999)
break; // Exit loop before 20 numbers
// Count Postive and Negative Numbers
if(number < 0)
negatives++;
else
positives++;
// Count Evens, Odds and Zeros
//Step 3c
switch (number % 2)
{
case 0:
evens++;
if (number == 0)
zeros++;
case 1:
case -1:
odds++;
} //end switch
} //end for loop
cout << endl;
// Display the results ....
//Step 4
cout << "There are " << evens << " evens, "
<< "which includes " << zeros << " zeros."
<< endl;
cout << "The number of odd numbers is: " << odds
<< endl;
cout << "The number of positive numbers is: " << positives
<< endl;
cout << "The number of negative numbers is: " << negatives
<< endl;
// Use Holdscreen to make sure the results are visible ....
char holdscr; // This character and section is to hold screen open
cout << "\n\n\tPress a character and Enter to exit program. ";
cin >> holdscr;
return 0;
}
I am debugging this program. There were originally 6 errors in the program. I've found four of them as they were syntax errors. The compiler doesn't show any error but the program isn't working either.
The program is supposed to store 20 numbers and in the end tell you how many of them were even, odd, zero, negative, and positive. I am just a beginner in C++. I have tried every possible way to solve it from my side but I cannot get it to work. I have looked up every code and syntax on Google why it works that way but found no help. Any help here would be highly appreciated.
If you enable warnings when you compile then the compiler will helpfully point out certain mistakes in your code, and if it's in a good mood it may even suggest a solution:
<stdin>:46:23: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if(number = 99999)
~~~~~~~^~~~~~~
<stdin>:46:23: note: place parentheses around the assignment to silence this warning
if(number = 99999)
^
( )
<stdin>:46:23: note: use '==' to turn this assignment into an equality comparison
if(number = 99999)
^
Always compile with warnings enabled (e.g. gcc -Wall ...) - it will save you a lot of time and debugging effort in the long run.
Using switch statement create a code that output remainders( 0, 1, 2, 3 and others) when divided by 8. User inputs 20 integer from 0 till 99. Each remainder should show its total count.
Eg :This is how the output should be.
Total number with remainder 0 is 4.
Total number with remainder 1 is 6.
Total number with remainder 2 is 5.
Total number with remainder 3 is 3.
Total number of other remainder is 2.
/
#include <iostream>
using namespace std;
int main()
{
int i, x[20];
cout << "Enter 20 integer numbers from 0 to 99: " <<endl;
for (i=1;i<=20;i++)
{
cout << "Input " << i <<":";
cin >> x[i]; // above this code, its working.
}
int remainder ; // From here im not sure how i should do it
switch (remainder)
{
case x[i] % 8 == 0 :
cout << "Total number with remainder zero is " << endl ;
break;
case x[i] % 8 == 1 :
cout << "Total number with remainder one is " << endl ;
break;
case x[i] % 8 == 2 :
cout << "Total number with remainder two is " << endl ;
break;
case x[i] % 8 == 3 :
cout << "Total number with remainder three is " << endl ;
break;
default :
cout << "Total of others is " << endl ;
}
return 0 ;
}
I have the general idea of the switch statements. I'm new to c++ and also to this website. Between the errors are at case part. It says i cant use x[i]. So should i just use x or other integer? Im not sure how to count the total number for each case. should i be using count++ ?
Switch statements are supposed to have a condition to test and then execute commands based on the results. The problem here is that you are testing a variable that does not have a value. The parentheses contain the data being tested. The cases are to execute given commands based on the resulting value. The thing you are testing here is x[i] % 8. This should go between in the parentheses. The case should just have the value attached to it.
switch (x[i] % 8) {
case 0: //...
case 1: //...
case 2: //...
case 3: //...
default: //...
}
case will test whether the result of the action taken in the parentheses equal its assigned value (e.g. 0, 1, 2, 3, or default) and execute the assigned command.
I have these block of codes that belong to a NIM subtraction game. The thing that I would like to implement is that user is going to be able play the game as long as he/she wants. Simply if user enters 999 program will exit, otherwise user will be playing until he/she enters 999. Here is my block of codes. I am not sure that I make a logical mistake or I need to add some specific exit code. Thanks for your time and attention.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int total, n;
while(true){
cout << "Welcome to NIM. \nEnter 999 to quit the game!\nPick a starting total: ";
cin >> total;
if(total==999)
break;
while(true){
//pick best response and print results.
if ((total % 3) == 2)
{
total = total - 2;
cout << "I am subtracting 2." << endl;
}
else
{
total--;
cout << "I am subtracting 1." << endl;
}
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "I win!" << endl;
break;
}
// Get user’s response; must be 1 or 2.
cout << "Enter num to subtract (1 or 2): ";
cin >> n;
while (n < 1 || n > 2)
{
cout << "Input must be 1 or 2." << endl;
cout << "Re-enter: ";
cin >> n;
}
total = total - n;
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "You win!" << endl;
break;
}
}
}
return 0;
}
You are modifying total inside the loop. Just test after cin>>total at the beginning if total==999 and break if true, i.e.
if(total==999)
break;
and replace the do-while loop by a while(true){}
In the do-while loop you are trying to compare character literal '999' with variable total that has type int.
}while(total!='999');
Though this code is valid its result can be something else than you are expecting. Values of character literals with more than one symbol are implementation defined.
You have to write
} while ( total != 999 );
Also if the player will enter 999 you start to play with him though you have to exit the game.
So in my opinion it is better to use while loop. For example
while ( true )
{
cout << "Welcome to NIM. \nEnter 999 to quit the game!\nPick a starting total: ";
cin >> total;
if ( total == 999 ) break;
// ...
}
you have to do three corrections in your code to make it right
first you have to check if total is equal to 999, then break in your do loop just after getting the total from user
second - you have to put same condition in your first while loop
and lastly - instead of while(total!='999') u shall write while(total!=999) because it is integer