Hello im stuck at SUBTRACTION AND DIVITION AND I CANT FIGURE OUT WHAT CODE to use because when I try to subtract 10 i inputed it then it will loop since the while condition is not meet which it needs to be negative to terminate the loop and i inputed 2 for the second number then loop again then i putted -number which lead to terminate loop and subtract all the number but the result is -12 its always wrong in every number cant figure out why Please help
Also with divition, only my addition is working havent started the divition cuz i cant figure out how
#include <iostream>
using namespace std;
int amt2, total;
double subNumbers();
double amt=1;
double number=0;
int main() {
int chc=0;
int amt = 0;
int amt2 = 1;
cout << "Welcome again User!\n";
cout << "______________________________________________________________\n" << endl;
cout << "Mathematical Operations(Improved):\n\n";
cout << "\t[1]-Addition" << endl;
cout << "\t[2]-Subtraction" << endl;
cout << "\t[3]-Multiplication" << endl;
cout << "\t[4]-Division\n" << endl;
cout << "______________________________________________________________\n" << endl;
cout << "Type the number corresponding to your chosen operation: ";
cin >> chc;
```
switch (chc) {
case 1:
```
system ("cls");
cout << "\n\n\tOperation chosen: Addition";
cout << "\n______________________________________________________________" << endl;
cout << "\n\nInput positive numbers to use the operation and input a negative number to end the operation.\n\n";
cout << "Enter your number: ";`
cin >> number;
while (number >= 0) {
// add all positive numbers
amt += number;
// take input again if the number is positive
cout << "Enter another number: ";
cin >> number;
}
// display the sum
cout << "\nThe sum of all the numbers is: " << amt << endl;
break;
```
case 2:
system ("cls");
cout << "\n\n\tOperation chosen: Subtraction";
cout << "\n______________________________________________________________" << endl;
cout << "\n\nInput positive numbers to use the operation and input a negative number to end the operation.\n\n";
do{
cout << "Enter your number: ";
cin >> number;
amt=number-number ;
}while (number >= 0);// subtract all positive numbers
// display the difference
cout << "\nThe difference of all the numbers is: "<<amt;
return 0;
}}
```
enter code here
You are subtracting number from number:
amt = number - number; // Which is always 0
So that's why amt == 0 always.
So just change your loop to this:
while (true) {
cout << "Enter your number: ";
cin >> number;
if (number < 0) break;
if (amt == 0) amt = number;
else if (number >= 0) amt -= number;
}
What this does is that if amt == 0, then set amt to number. I have done this because as the default value of amt is 0 (due to int amt = 0;), when amt == 0, then we can assume that the user has entered the first number, and thus we can set amt to number. And then we can use -= operator, which basically means:
amt = amt - number;
But before all this, using if (number < 0) break; we can check if the user has entered a negative number, and if the user has entered a negative number, then the break keyword will break out of the while loop.
Related
I am trying to create a loop that allows the user to enter as many elements to the array as they would like then sum up those elements. I need the loop to terminate when the user enters a negative number. How would I go about terminating this?
double sum = 0;
double group[] = { 0 };
for (int i = 0; i >= 0; i++) {
cout << "Please enter employee salary. Enter negative number to end." << endl;
cout << "Employee " << i + 1 << ": $";
cin >> group[i];
if (i < 0) {
break;
}
sum += group[i];
}
cout << "The total salary ouput for Ernest Inc is: $" << fixed << showpoint << setprecision(2) << sum << endl;
I need the loop to terminate when the user enters a negative number.
For that a while loop would be better than for. You should also use vector which allows arbitrary number of items.
Something like this:
vector<double> group;
double salary;
while (true)
{
cout << "Please enter employee salary. Enter negative number to end." << endl;
cout << "Employee " << i + 1 << ": $";
cin >> salary;
if (salary<0)
{
break;
}
group.push_back(salary);
sum += salary;
}
Hey so this is really getting on my nerves.
I'm trying to validate user input within a loop.
I need the user input to be between 0 and 60. I can validate it no problem but what I want it to do is re-ask the previous question if the input is incorrect, you know? like repeat the loop if that makes sense
int main()
{
//Constants
const int MAXROUNDS = 4;
const int NUMARCHERS = 3;
//Variables
int archerNum;
int roundNum;
double score;
double total;
//Start of outer loop, this loop displays each Archer
for (archerNum = 1; archerNum <= NUMARCHERS; archerNum++)
{
total = 0; //This clears the total for the archer
//Start of second loop, this loop displays each round
for (roundNum = 1; roundNum <= MAXROUNDS; roundNum++)
{
cout << "Enter Round " << roundNum << " score for Archer "
<< archerNum << ": ";
cin >> score;
if (score < 0 | score > 60)
{
cout << "ERROR! Number must be between 0 and 60!";
}
}
total = score + score + score + score; //This calculates the total score for the tournament
cout << "\nThe total score for archer " << archerNum << " is: "
<< total << "\n\n";
}
return 0;
}
This is my code ^
Now I have tried so many things. I've looked through my textbook and I've googled everything but I cant seem to find the answer.
I've tried putting the error message in a do-while loop
i've used if-else statements
i've used while loops
I think I've literally used every different type of loop there is and I still cant seem to figure it out and I'm becoming very frustrated.
Thanks in advance
Here is a simple version of just the number input and error message:
//#include "pch.h" if using Visual Studio 2017
#include <iostream>
using namespace std;
int main(){
cout << "Please enter a number between 0 and 60." << endl;
int input;
cin >> input;
while(input < 0 || input > 60 || cin.fail()){ //Using cin.fail() here in case the user enters a letter or word
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cerr << "Number must be between 0 and 60. Please try again." << endl;
cin >> input;
}
return 0;
}`
Alternatively, you could use a goto statement though, as I am sure many others on this site will tell you, that is not recommended as it leads to the infamous 'spaghetti code'.
Simply add roundNum -= 1; inside the validation If statement. It will make the counter decreased by 1, and re-ask the previous question
//Start of second loop, this loop displays each round
for (roundNum = 1; roundNum <= MAXROUNDS; roundNum++)
{
std::cout << "Enter Round " << roundNum << " score for Archer "
<< archerNum << ": ";
std::cin >> score;
if (score < 0 || score > 60)
{
std::cout << "ERROR! Number must be between 0 and 60!"<<endl;
roundNum -= 1; //or roundNum--
}
}
Try:
bool inputError;
do {
inputError = false;
std::out << "Enter Round "
<< roundNum
<< " score for Archer "
<< archerNum << ": ";
if (std::cin >> score) {
if (score < 0 || score > 60)
{
std::cout << "ERROR! Number must be between 0 and 60!";
inputError = true;
}
}
else {
std::cout << "ERROR! Your input must be a number";
inputError = true;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
}
} while(inputError == true);
I am currently working on a programming assignment and am having trouble with checking the input placed by the user. The program is where you enter two positive numbers only, however when I enter a character, such as 'a' as my first "number", the program accepts it and outputs it as if I entered a zero. It should output "Invalid number: Numbers must be positive integer." Can someone tell me what I am doing wrong? Thank you!
//Program where user enters two positive numbers
//and program will display various things.
#include <iostream>
using namespace std;
int main()
{
//Displays information of what program will do
cout<< "Practice with iterations\n\n"
<< "The function of this program is, given 2 positive numbers, the"
<< " program";
cout<< "\nwill display the following\n\n";
cout<< "\t1. All even numbers between firstNum and secondNum.\n"
<< "\t2. All odd numbers between firstNum and secondNum.\n"
<< "\t3. Sum of all even numbers between firstNum and secondNum.\n"
<< "\t4. Sum of all odd numbers between firstNum and secondNum.\n"
<< "\t5. All prime numbers between firstNum and secondNum.\n"
<< "\t6. Factorial of the secondNum.\n"
<< "\t7. The numbers and their squares between firstNum and "
<< "secondNum."<< endl;
//Declare first and second number variables
int firstNum;
int secondNum;
bool flag= true; //Set to true
char x; //Use to see if value entered is letter
//Ask user to input values
cout<< "\n\nEnter the first number:\t\t";
cin>> firstNum;
if (cin.fail())
{
cin.clear();
cin.ignore(256,'\n');
flag= 0;
}
cout<< "Enter the second number:\t";
cin>> secondNum;
if (cin.fail())
{
cin.clear();
cin.ignore(256,'\n');
flag= 0;
}
//If user puts wrong input
if (firstNum>secondNum)
cout<< "\nError: First number must be < second number.\n";
else if (firstNum<0 || secondNum<0)
cout<< "\nError: Invalid number: Number must be positive.\n";
else if (firstNum==x || secondNum==x)
cout<< "\nError: Invalid number: Numbers must be positive integer.\n";
else
{
cout<< "\nYou entered: "<< firstNum<< " and "<< secondNum;
}
return 0;
}
if (firstNum==x || secondNum==x)
cout<< "\nError: Invalid number: Numbers must be positive integer.\n";
this test is wrong x is not initialized and it doesn't really make sense..plus you have used the flag to test the fail input case i assume so your code should be like this
#include <iostream>
using namespace std;
int main()
{
//Displays information of what program will do
cout << "Practice with iterations\n\n"
<< "The function of this program is, given 2 positive numbers, the"
<< " program";
cout << "\nwill display the following\n\n";
cout << "\t1. All even numbers between firstNum and secondNum.\n"
<< "\t2. All odd numbers between firstNum and secondNum.\n"
<< "\t3. Sum of all even numbers between firstNum and secondNum.\n"
<< "\t4. Sum of all odd numbers between firstNum and secondNum.\n"
<< "\t5. All prime numbers between firstNum and secondNum.\n"
<< "\t6. Factorial of the secondNum.\n"
<< "\t7. The numbers and their squares between firstNum and "
<< "secondNum." << endl;
//Declare first and second number variables
int firstNum;
int secondNum;
bool flag = true; //Set to true
//Ask user to input values
cout << "\n\nEnter the first number:\t\t";
cin >> firstNum;
if (cin.fail())
{
cin.clear();
cin.ignore(256, '\n');
flag = 0;
}
cout << "Enter the second number:\t";
cin >> secondNum;
if (cin.fail())
{
cout << "lol" << endl;
cin.clear();
cin.ignore(256, '\n');
flag = 0;
}
if (flag) {
if (firstNum > secondNum)
cout << "\nError: First number must be < second number.\n";
else if (firstNum < 0 || secondNum < 0)
cout << "\nError: Invalid number: Number must be positive.\n";
else
{
cout << "\nYou entered: " << firstNum << " and " << secondNum;
}
}
else cout << "Error input" << endl;
return 0;
}
If there is an error in reading the input, you have the first steps correctly accounted for -- clear the input stream and clear the error state of cin. What you are missing is reading something valid into the variable. For that you need a loop.
while (true )
{
//Ask user to input values
cout<< "\n\nEnter the first number:\t\t";
// Try to read the input. If it is successful, break out of the loop.
if ( cin>> firstNum )
{
break;
}
// Clear the error flag. Clear the input stream. Try again.
cin.clear();
cin.ignore(256,'\n');
}
Do the same thing for the second number.
I'm very sorry for the super newbie question, but I cannot for the life of me understand how to make a do while loop repeat. I changed a while loop into a do while loop and now I don't know how to get it to ask "would you like to repeat Y or N?" any explanation?
I've read various posts that accomplish a do while loop repeat, but they don't make sense to me.
Am I essentially going to wrap this code into another do while loop? Do I move the boolean expression to before the while?
#include <iostream>
using namespace std;
int main(void)
{
int x;
int count = 0;
int N;
double sum = 0;
double average;
char ans;
{
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; //
} while (count < N);
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
else {
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
}
cout << "Would you like to enter more values to calculate your grade average?\n";
system("pause");
return 0;
}
}
can do this:
char repeat='y';
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
for(int i=0;i<n;i++){
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; //
}
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
else {
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
}
cout << "Would you like to enter more values to calculate your grade average?\n";
cin>>repeat;
}while(repeat=='y');
May be this is what you need, with char YorN you are considering if to continue or break the inner do-while.
#include <iostream>
using namespace std;
int main(void)
{
int x;
int count = 0;
int N;
double sum = 0;
double average;
char ans;
char YorN;
do{
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; //
} while (count < N);
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
else {
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
}
cout << "Would you like to enter more values to calculate your grade average?\n";
cin>>YorN;
} while (YorN=='Y');
return 0;
}
Although there are a ton of ways to do it better, this code allows me to explain what is happening. Do-While loops are definitely pretty tricky. However, just remember that a do-while loop is designed to run at least once.
In the case of our code, we set up if statements to test against running code where it is not appropriate.
Take a look at how the very first if statement is N > 0, the if-statement does execute, please do not forget that. Once more for emphasis, the if statement DOES execute, it just results in false.
With that being said, you use a do-while loop when you want your code block to execute AT LEAST once. Notice how our while statement has two things we're testing for, one, is the answer 'Y' from the user to continue, and if it is, is the newly inputted N value greater than 0?
You might be wondering if the inner most if statement ever executes at least once, well the answer is it depends on the previous if statement result if(N > 0) and if(count == N && N != 0) both execute once every single time the while loop stays true. However that nested if depends on it's parent result.
I hope this cleared some things up for you on do-while loops.
#include <iostream>
using namespace std;
int main(void)
{
int x;
int count = 0;
int N;
double sum = 0;
double average;
char ans = 'Y';
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
if(N > 0){ //THIS IF STATEMENT WILL ALWAYS RUN AT LEAST ONCE
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++;
}
if(count == N && N != 0) {//THIS IF STATEMENT WILL ALSO ALWAYS RUN AT LEAST ONCE
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
cout << "Would you like to enter more values to calculate your grade average?\n";
cin>>ans;
if(ans == 'Y') {//This one depends on it's parents result.
x = 0;
N = 0;
sum = 0;
count = 0;
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
}
}
} while (ans == 'Y' && N != 0);
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
system("pause");
return 0;
}
I see a ton a questions for converting for loops to while and do while loops, but I cant seem to find anything on converting while loops to do while loops in C++. It still needs to maintain the same function as the original code as well.
Here is the original code:
int number, product = 1, count = 0;
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number;
while (number != 0)
{
product = product * number;
count++;
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number;
}
if (count > 0)
{
cout << endl << "The product is " << product << "." << endl;
}
By moving it around, I was able to end up here, but I keep ending up with errors. When I run the program, it prompts me to enter a while number, like expected. If I enter a valid number, it loops and asks me the same question. Then when I enter 0, it kicks out as usual, but it displays that the product is 0 no matter the numbers entered before.
Here is my attempt at adjusting it into a do while loop:
int main()
{
int number, product = 1, count = 0;
do
{
cout << "Enter a whole number to be included in the product" << endl << "or enter 0 to end the input: ";
cin >> number;
product = product * number;
count++;
}
while (number != 0);
{
if (count > 0)
cout << endl << "The product is " << product << "." << endl;
}
}
In the do .. while loop when you insert 0, first you multiply product by 0, than it exists. Therefore the product is always 0.
Move the product before:
int count = -1, number = 1, product = 1;
do
{
count++;
product = product * number; // you can use product *= number;
cout << "Enter a whole number to be included in the product" << endl << "or enter 0 to end the input: ";
cin >> number;
}
while (number != 0);
if (count > 0)
cout << endl << "The product is " << product << "." << endl;
Note: my code does not use additional if and still preserve the same functionality.
test number!=0 before assigning product = product*nuumber
otherwise, when user enters 0, you multiply by 0 and exit the loop
The problem is that in the do-while version, when the user inputs 0 this line:
product = product * number;
is executed, whereas in the while version not.
Because of this the product will always be 0.
If the number is 0 just don't multiply product.
Your problem was the number input on exit is 0, which makes your whole product equal to 0. Try this logic:
#include <iostream>
int main() {
int number = 0, product = 1, count = 0;
do {
std::cout << "Enter a whole number to be included in the product" << std::endl << "or enter 0 to end the input: ";
std::cin >> number;
if (number > 0) {
product = product * number;
count++;
}
} while (number != 0);
{
if (count > 0)
std::cout << std::endl << "The product is " << product << "." << std::endl;
}
}
If you just want to solve the problem that you are getting a 0 as your answer, then the problem is due to the following lines
cin >> number;
product = product * number;
you take the number which is 0 and multiply it with the product and obviously the result will be 0.
you can fix it by putting a break statement.
cin >> number;
if(number == 0)
break;
product = product * number;
However, in general I am not sure what you are achieving by trying to solve this problem i.e. converting a while to a do-while.
int number, product = 1, count = 0;
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number; // you enter a non-0 number here
while (number != 0) // you now loop until you hit 0 ...
{
product = product * number;
count++;
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number; // you overwrite the non-0 number you had previously input
}
if (count > 0)
{
cout << endl << "The product is " << product << "." << endl;
}
Without knowing the full context of your program, I'm guessing here, but you can probably rewrite it as:
int number = 0, product = 1, count = 0;
do
{
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number;
if (number != 0)
{
count++;
product *= number;
}
} while (number != 0); // exit the loop when you have a non-zero entry
if (count > 0)
{
cout << endl << "The product is " << product << "." << endl;
}
Or ...
int number = 0, product = 1;
do
{
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number;
if (number != 0)
{
product *= number;
}
} while (number != 0); // exit the loop when you have a non-zero entry
cout << endl << "The product is " << product << "." << endl;
You can avoid the 2nd condition since you are excluding 0 from potential inputs, and simply always output a product.
You are increasing count regardless of the input you get. First check if the input was zero (your abort input).
Change
count++
to
if (number)
count++;