Yes or No While Loops c++ - c++

I am writing a program that allows the user to input an integer, which I then reverse and output back to them. I would like the program to run again at the user's request and allow them to enter another integer, but I'm unable to do so.
Here is what I expect my program to be able to do:
Enter a positive integer: 38475
This integer in reverse is 57483.
Would you like to do this again? (y/n) y
Enter a positive integer: 9584
This integer in reverse is 4859.
Would you like to do this again? (y/n) n
And here is my code, which currently handles reversing the input.
#include <iostream>
using namespace std;
int main()
{
int num, i = 10;
cout << "Enter a positive integer: ";
cin >> num;
cout << " This integer in reverse is ";
do
{
cout << (num%i) / (i / 10);
i *= 10;
} while ((num * 10) / i != 0);
return 0;
}
How can I have my program run multiple times based on user input?

Initialize a char to 'y'. Obtain the user input and set that to the char after the user provides the input. The while loop should look something like while (answer == 'y'). This way it'll run at least once.

As Ceelos points out in their answer you can do this with another do while loop using a single char and ask the user whether they wish to repeat the program or not. I have added an example for clarity:
int main()
{
char repeat = 'n';
do
{
int num, i = 10;
cout << "Enter a positive integer: ";
cin >> num;
cout << " This integer in reverse is ";
do
{
cout << (num%i) / (i / 10);
i *= 10;
} while ((num * 10) / i != 0);
// Ask the user if they wish to play again
cout << endl << "Would you like to have another turn?" << endl;
// Get their answer
cin >> repeat;
} while (repeat == 'y');
return 0;
}

Related

How to print product of all inputted numbers using a loop?

int main() {
cout << "Enter some numbers fam! " << endl;
cout << "If you wanna quit, just press q" << endl;
int n{ 0 };
int product = 1;
char quit = 'q';
while (n != 'q') {
cin >> n;
product = product* n;
cout <<"The product is : " << product << endl;
}
cout << endl;
cout << product;
return 0;
}
Whenever I print it out and cut the code using 'q', it prints me an infinite amount of "The product is 0". Also, how can I print out the final product of all numbers at the end?
So, there are some problems in your code.
First, you are taking input and assigning it to an int, which might not have been a problem, but you are also comparing the int to a char(which will cause problems in your case)
int n{ 0 };
while(n != 'q') {
cin >> n;
}
To solve that, you can make the n a string and then convert it into an integer with stoi(n) to use with the calculation
string n; // don't need to initialize a string, they are initialized by default.
int product = 1;
cin >> n; // Taking input before comparing the results
while(n != "q") { // Had to make q a string to be able to compare with n
product *= stoi(n); // Short for product = product * stoi(n)
cout <<"The product is : " << product << endl;
cin >> n; // Taking input for the next loop round
}
cout << endl;
cout << product;

How do I keep asking the user a question over and over again until they enter the correct field of value?

I am a rookie coder here and I can't seem to figure out what to add to my code here to get it right. It is supposed to ask the user again if they do not answer the question "Do you want to make another calculation Y or N?" correctly. I want it to repetitively ask the user to enter y or n if they enter something else. I feel like it is obvious I am just missing it. This is for school, to be clear.
I've tried nesting a do while loop and an if statement but only to get run time errors
#include <iostream>
using namespace std;
int main() {
int base, exponent;
long int result = 1;
char choice;
int i;
do
{
cout << "This program raises a number to a specific power." << endl;
cout << "\nEnter a base integer greater than 1: ";
cin >> base;
cout << "\nEnter an exponent integer to raise that number to: ";
cin >> exponent;
for (i = 1; i <= exponent; i++)
{
result = result * base;
}
cout << "\n" << base << " to the power of " << exponent << " = " << result << endl;
result = 1;
// ***** HERE IS WHERE I NEED HELP, WHAT TO
// DO IF THEY DONT ENTER Y OR N.....
cout << "\nWould you like to make another calculation? Y or N: ";
cin >> choice;
cout << endl;
}
while (choice == 'y' || choice == 'Y');
cout << "Good bye, then. Have a good day.\n" << endl;
return 0;
}
When I tried adding a nested do while loop, and entered a character answer other than y or n, it would go to a part of the program it should not have.
*this is my first question so I hope I've done this correctly
You can use another do-while loop to wrap the input section.
do
{
cout << "This program raises a number to a specific power." << endl;
cout << "\nEnter a base integer greater than 1: ";
cin >> base;
cout << "\nEnter an exponent integer to raise that number to: ";
cin >> exponent;
for (i = 1; i <= exponent; i++)
{
result = result * base;
}
cout << "\n" << base << " to the power of " << exponent << " = " << result << endl;
result = 1;
do
{
cout << "\nWould you like to make another calculation? Y or N: ";
cin >> choice;
cout << endl;
} while (choice != 'y' && choice != 'Y' && choice != 'n' && choice != 'N');
}
while (choice == 'y' || choice == 'Y');
Learn to think organically here. Let me do a procedural approach.
We begin by bringing your formulations into a more technical form, until it is syntactically and semantically working. Let's start by transforming it into this:
void process_things()
{
...
while(still_require_answer)
{
ask_for_answer();
}
...
}
This is very close to how you formulate it verbally, yes? Now, let's flesh it out.
string ask_for_answer(bool& still_require_answer);
void process_things()
{
...
string answer = "";
bool still_require_answer = true;
while(still_require_answer)
{
answer = ask_for_answer(still_require_answer);
}
...
}
// hope you understand the concept of a reference here,
// that is what the ampersand (&) does, if not, ask
string ask_for_answer(bool& still_require_answer)
{
string answer = ""; // always initialize
cout << "State answer: ";
cin >> answer;
cout << endl;
if(answer == "Y" or ...)
{
still_require_answer = false;
}
return answer;
}
Hope this helps you. In the long run, you might want to go OOP and use classes here. The code here is a little bit verbose, but orderly.
Note that I have put the routine in a new function process_things. Anything that is more than a few lines which you can name you should think about making a function (or a class method). Your main should be quite small. Cutting things down into smaller units helps you keeping thisng orderly and makes the design of each single unit easy (divide-and-conquer) and allows you to quicker locate problems as you can test every function separately (later, this leads to automated unit tests).
One could also take the while and put it into it's own function string ask_until_valid_answer();, and if we do that, dissolve ask_for_answer and put it's content there. What I want to focus on is to have it organically, that is use self-descriptive names which explain the program while reading it, and to cut the program into understandable units. Here would be this other layout:
string ask_until_valid_answer();
void process_things()
{
...
string answer = ask_until_valid_answer();
...
}
string ask_until_valid_answer()
{
string answer = "";
bool still_require_answer = true;
while(still_require_answer)
{
cout << "State answer: ";
cin >> answer;
cout << endl;
if(answer == "Y" or ...)
{
still_require_answer = false;
}
}
return answer;
}

C++ total keeps going up

Hello this is my first program with a do-while loop and its taken me a little while to get it down. I need to have the user enter 2 numbers, and raise the first number to the second number. I have finally got the coding to ask if "they would like to raise another number by a power?" and when they say yes and enter 2 new numbers the total adds the total from the first 2 numbers entered with the second set of numbers and so on. Can someone help me out with this problem? Here is the coding and a picture to help y'all out!
#include <iostream>
using namespace std;
int main()
{
int num;
int pow;
int p;
int power = 1;
char yesno = 'y' || 'Y';
do
{
cout << "Enter a number: ";
cin >> num; "\n";
cout << "Enter the power to raise: ";
cin >> pow; "\n";
for (p = 1; p <= pow; p++)
{
power = power * num;
}
cout << "The total is: " << power << endl;
cout << "\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
} while (yesno != true);
}
The problem of the ever-increasing answer is that power is not being reset inside the do-while loop, so the last value is being carried forward into the next loop. You need reset it at the top of the loop.
Another problem with the code is that the exit condition would never occur.
Try this instead:
int main()
{
int num;
int pow;
int p;
int power;
char yesno;
do
{
power = 1; // <<<<<< reset power here
cout << "Enter a number: ";
cin >> num; "\n";
cout << "Enter the power to raise: ";
cin >> pow; "\n";
for (p = 1; p <= pow; p++)
{
power = power * num;
}
cout << "The total is: " << power << endl;
cout << "\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
} while (yesno == 'y' || yesno == 'Y'); // <<<<< test for 'yes' response
}
When you reach line } while (yesno != true); and loop back to do {, the variable power still holds the previous num^pow. You will need to assign power = 1 after do {.
#include <iostream>
// you also need
#include <cmath> // for pow()
using namespace std;
int main()
{
// int num; Declare variables where they're used. As locally as possible.
// int pow;
// int p;
// int power = 1;
// char yesno = 'y' || 'Y'; I don't know what you were trying to do here
// the expression 'y' || 'Y' will always be true
// and evaluate to some value different from null
// wich will be assigne to yesno. But with no con-
char yesno; // sequences since it later gets overwritten by
do // cin >> yesno; There is no need to initialize
{ // this variable.
cout << "Enter a number: ";
int num;
cin >> num; "\n"; // the statement "\n"; has no effect.
cout << "Enter the power to raise: ";
int pow;
cin >> pow; "\n"; // again. no effect.
// for (p = 1; p <= pow; p++) as user4581301 has pointed out in the
// comments it is more ... natural in C
// to loop from 0 to < max:
int power = 1; // now its time to declare and define power ;)
for(int p = 0; p < pow; ++p) // notice that you can declare variables
{ // in the init-statement of a for-loop
// power = power * num; shorter:
power *= num;
}
cout << "The total is: " << power << /* endl; + 2 x '\n' gives: */ << "\n\n\n";
// cout << "\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
// } while (yesno != true); that condition will most likely always be true
// since the user would have a hard time to input
// a '\0' character, which would evaluate to false
// better:
} while(yesno == 'y' || yesno == 'Y' );
}
done.
Without clutter:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
char yesno;
do {
cout << "Enter a number: ";
int num;
cin >> num;
cout << "Enter the power to raise: ";
int pow;
cin >> pow;
int power = 1;
for(int p = 0; p < pow; ++p)
power *= num;
cout << "The total is: " << power << "\n\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
} while(yesno == 'y' || yesno == 'Y' );
}

IF or WHILE for numerical input checker

I've been working on a program that calculates the mean of the user's inputs. I couldn't figure out yet, what to use for the input checker. I can't use arrays or strings yet. How do I check that both inputs are numerical values? And if they are not; how do I ask again for the correct input?
#include <iostream>
using namespace std;
int main()
{
// Get number from user
int input = 0;
double accumulator = 0;
double mean;
cout << "How many numbers would you like me to average together?\n";
cin >> input;
if (input >= 0){ //to check if input is a numerical value
// Compute and print the mean of the user input
int number = 1;
double x;
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
if (x < 0 || x > 0){ //to check if x is a numerical value
accumulator = accumulator + x;
}
else {
cout << "Input incorrect"<< endl;
}
number = number + 1;
}
mean = accumulator / input; // formula corrected
cout << "The mean of all the input values is: " << mean << endl;
cout << "The amount of numbers for the average calculation is: " << input << endl;
}
else {
cout << "Input incorrect"<< endl;
}
return 0;
}
You can use cin.fail to check for errors. Note that if user inputs a number followed by letters, lets say 123abc, then x will be stored as 123 but abc remains in the input buffer. You may wish to clear that right away so abc doesn't appear in the next loop.
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
bool error = cin.fail();
cin.clear();
cin.ignore(0xFFFF, '\n');
if (error)
{
cout << "Input incorrect" << endl;
continue;
}
accumulator = accumulator + x;
number = number + 1;
}
Alternatively you can initialize x. For example
double x = numeric_limits<double>::min();
cin >> x;
cin.clear();
cin.ignore(0xFFFF, '\n');
if (x == numeric_limits<double>::min())
{
cout << "Input incorrect" << endl;
continue;
}
If error occurs then x remains unchanged and you know there was an error, because it is unlikely that the user inputs a number matching numeric_limits<double>::min()
Not related to this issue, but you should also account for divide by zero error.
if (input == 0)
mean = 0;//avoid divide by zero, print special error message
else
mean = accumulator / input;

problems with switch statement involving functions [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
This program is not prompting me for input. I need help with defining, and calling functions properly. menu() is supposed to display a string of text, and ask the user to select a number 1-4, and if the user enters a number outside of that it will ask the user to enter an appropriate number until 1-4 is entered. The value of menu() will be stored in a variable 'choice' and be used in a switch statement.
Inside of the switch statement the corresponding choice functions[getSum(), getFactor(), getExpo(), and exit()] are called. They each need to ask the user for an integer, and perform some arithmetic, and return some output text to the user with the calculated value.
All of this is inside of a do while loop repeating this process, until the user chooses the option 4 to quit the program, where the exit() function will return a string exit message to the user and then the program will terminate.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int menu();
long int getSum();
long int getFactor();
long int getExpo();
string exit();
int main()
{
const int SUM = 1, // Summation choice
FACTOR = 2, // Factorial choice
EXPO = 3, // Exponential choice
QUIT = 4; // Exit choice
int choice; // Numerical menu choice
long int sums, facts, expos;
string quits;
// Force the console to print standard notation
cout << fixed << setprecision(0);
// Do-While loop controlled by the users choices
do
{
choice = menu();
switch (choice) // Start switch option
{
case SUM: // 1st choice
sums = getSum();
break;
case FACTOR: // 2nd choice
facts = getFactor();
break;
case EXPO: // 3rd choice
expos = getExpo();
break;
case QUIT: // 4th choice
quits = exit();
break;
default: // Default choice
// Error message for input outside domain
cout << "Please make a selection of either 1,2,3 or 4.\n\n";
cin >> choice; // Repeat attempt to gather input from user
}
}
while (menu() != QUIT);
return 0;
}
int menu()
{
int choice;
cout << "\n\t\tMathematical Menu\n" // Header
<< "1) Summation\n" // 1st choice
<< "2) Factorial\n" // 2nd choice
<< "3) Exponential\n" // 3rd choice
<< "4) Exit Program\n\n" // 4th choice
<< "Please make a selection\n" // Ask user for imput choice
<< "of either 1,2,3 or 4.\n\n";
cin >> choice; // Gather input from user
return choice;
}
long int getSum()
{
int total = 0, userNum, counter;
// Ouput statement to user
cout << "Please enter a positive integer value greater than 0 \n"
<< "and less than 10,000,000.\n\n";
cin >> userNum; // Repeat attempt to gather input from user
// Compare input to domain
if (userNum < 0 || userNum > 10000000)
{
// Error message for input outside domain
cout << "Please check your entry and try again.\n\n";
cin >> userNum; // Repeat attempt to gather input from user
}
// Perform arithmetic summation
for (counter = 1; counter <= userNum; counter++)
{
total += counter; // Running count
}
cout << "The total value for the added numbers 1 to \n"
<< userNum << " is:\n"<<total;
return total;
}
long int getFactor()
{
int total, userNum, counter;
total = 1;
// Output statement to user
cout << "Please enter a positive integer from 0 \n"
<< "and less than 100.\n\n";
cin >> userNum; // Gather input from user
// Compare input to domain
if (userNum > 100 || userNum < 0)
{
// Error message if input is outside domain
cout << "Please check your entry and try again.\n\n";
cin >> userNum; // Repeat attempt to gather input from user
}
// Perform arithmetic factorial
for (counter = 1; counter <= userNum; counter++)
{
total *= counter; // Running count
}
// Display arithmetic output to user
cout << "The total value for the multiplied numbers 1 to \n"
<< userNum << " is:\n";
return total;
}
long int getExpo()
{
int total, userNum, counter;
total = 0;
// Output statement to user
cout << "Please enter a positive integer from 0 \n"
<< "and less than 100.\n\n";
cin >> userNum; // Gather input from user
// Compare input to domain
if (userNum > 100 || userNum < 0)
{
// Error message if input is outside domain
cout << "Please check your entry and try again.\n\n";
cin >> userNum; // Repeat attempt to gather input from user
}
// Perform arithmetic exponential
for (counter = 1; counter <= userNum; counter++)
{
total = pow(2.0, userNum); // Running count
}
// Display arithmetic output to user
cout << "The total value for the exponential function is \n";
return total;
}
string exit()
{
// Exit message
return "Don't be gone for too long...\n";
}`
Do not call menu() more than once: it will prompt the user twice.
Do not return anything from a function that does all the work anyway. Make it
void getExpo(){ ...; return; }
Call:
getExpo();