How to end my while loop? [duplicate] - c++

This question already has answers here:
Immediate exit of 'while' loop in C++ [closed]
(10 answers)
Closed 6 years ago.
Hey can anyone lend me a hand? How can I make my loop end after the first calculation? After i complete one calculation such as addition, I would like to end it. Sorry for the noobie questions. I'm just learning loops now in my class. Greatly appreciated.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int numOne;
int numTwo;
int result;
string operation;
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
while (operation == "e" || operation == "E")
{
cout << "Operation type invalid." << endl;
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
}
while (operation == "+" || operation == "-" || operation == "*" || operation == "/")
{
cout << "Please enter integer one: ";
cin >> numOne;
cout << "Please enter integer two: ";
cin >> numTwo;
if (operation == "+")
{
result = numOne + numTwo;
cout << "The numbers you entered were " << numOne << "," << numTwo << endl;
cout << "The operation you chose was " << operation << "." << endl;
cout << "The operations result is " << result << "." << endl;
cout << "Your equation was: " << numOne << " " << operation << " " << numTwo << " = " << result << ".";
}
else if (operation == "-")
{
result = numOne - numTwo;
cout << "The numbers you entered were " << numOne << "," << numTwo << endl;
cout << "The operation you chose was " << operation << "." << endl;
cout << "The operations result is " << result << "." << endl;
cout << "Your equation was: " << numOne << " " << operation << " " << numTwo << " = " << result << ".";
}
else if (operation == "*")
{
result = numOne * numTwo;
cout << "The numbers you entered were " << numOne << "," << numTwo << endl;
cout << "The operation you chose was " << operation << "." << endl;
cout << "The operations result is " << result << endl;
cout << "Your equation was: " << numOne << " " << operation << " " << numTwo << " = " << result << ".";
}
else if (operation == "/")
{
if (numTwo == 0)
{
cout << "You cannot divide by zero!" << endl;
}
else
{
result = numOne / numTwo;
cout << "The numbers you entered were " << numOne << "," << numTwo << endl;
cout << "The operation you chose was " << operation << "." << endl;
cout << "The operations result is " << result << endl;
cout << "Your equation was: " << numOne << " " << operation << " " << numTwo << " = " << result << ".";
}
}
}
return 0;
}
I'm not allowed to use break. Is there another way?

You can end a while loop using...
break;
ie
if(!(operation == "e" || operation == "E")) {
break;
}
Normally to end a while loop the (EXPRESSION) in the following ie
while((EXPRESSION) == true) { execute_code_here();}
needs to evaluate to false. The expression can be made up of many logical pieces ie
while (a == b && c != d && f++ < 1000) {do_something_here();}
The break keyword is used to terminate a while loop early but this can also be achieved by adding something to the expression that allows you to terminate the while loop ie make the expression evaluate to false, this is normally done using a flag or a counter.
To achieve the same effect as break without using it you can use this technique with continue. You then use the flag or counter along with continue to achieve the same thing as break ie, this is a counter example
while(a == b && flag++ < 1000) {
if(this_returns_true()) {
flag = 10000;
continue;
}
/*The code here may not be executed*/
}
Using a boolean flag it would be...
while(a == b && flag == true) {
if(this_returns_true()) {
flag = false;
continue;
}
/*The code here may not be executed*/
}

Just change the while to if. There's no need for a loop if you only want to execute something once.

You can use break; with an if statement inside the while loop. So that if a condition is true you will break out from the while loop.
Example
if (operation != "e")
break;
If you're not allowed to use break, I suggest you don't use a loop. And just calculate it once.

I am not very experienced with C++ but I think you mean the break; statement
https://msdn.microsoft.com/library/37zc9d2w.aspx

Use
break;
This will end the loop each time. You can wrap an if statement around it to apply conditions for exiting.

If you have to use the while loop just add break; and that will break out of the loop. If you don't have to I would change that to an if statement. Example: if(varName == '+'){
Num1 + num2;}
Sorry for format, on mobile

The code block:
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
while (operation == "e" || operation == "E")
{
cout << "Operation type invalid." << endl;
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
}
Doesn't do what you're promising the user:
Please enter what operation you'd like to perform or e/E to end program:
If "e" or "E" is entered, the loop won't stop and ask for input again.
You probably want to have something like this:
do {
cin >> operation;
while (operation == "+" || operation == "-" || operation == "*" || operation == "/") {
// ...
}
} while(operation != "e" && operation != "E");
As for your silly restrictions not to use do {} while(); (kick your professor in the ass, do twice at least):
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
while(operation != "e" && operation != "E") {
if (operation == "+" || operation == "-" || operation == "*" || operation == "/") {
// ...
}
else {
cout << "Operation type invalid." << endl;
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
}
}

I guess that what you are actually trying to achieve is this.
The first loop should be refactored (ie: loop until operation is nether 'e' nor 'E'), the second loop should be an if-else-statement (checking whether the operation is valid).
int main()
{
int numOne;
int numTwo;
int result;
string operation;
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
while (operation != "e" && operation != "E") {
if (operation == "+" || operation == "-" || operation == "*" || operation == "/") {
// your valid operation code...
} else {
cout << "Operation type invalid." << endl;
}
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
}
return 0;
}

Related

Multiple OR conditions in while loop in C++

I am trying to put multiple OR conditions in my WHILE loop so that unless my "decision" variable is equal to "1" or "2", it will continue looping. However, even when I am entering "1" or "2", it still loops.
cout << "Would you like to add or subtract these numbers?"
<< endl
<< "(1) for addition"
<< endl
<< "(2) for subtraction"
<< endl
<< "Select one: ";
cin >> decision;
while ((decision != 1) || (decision != 2))
{
cout << "Please pick (1) for addition or (2) for subtraction: ";
cin >> decision;
}
if (decision == 1)
{
cout << firstNum << " + " << secondNum << " = " << firstNum + secondNum;
}
else if (decision == 2)
{
cout << firstNum << " - " << secondNum << " = " << firstNum - secondNum;
}
Individually the conditions work i.e.
while (decision != 1)
or
while (decision != 2)
But not when together. Am I using OR operator wrong?
I have only just started learning C++ so please bear with me, any advice would be much appreciated!
That would be while ((decision != 1) && (decision != 2)).
But I recommend this way.
bool decision_check(int decision) {
switch (decision) {
case 1:
cout << firstNum << " + " << secondNum << " = " << firstNum + secondNum;
return true;
case 2:
cout << firstNum << " - " << secondNum << " = " << firstNum - secondNum;
return true;
default:
cout << "Please pick (1) for addition or (2) for subtraction: ";
return false;
}
}
Use this function in while.

Can't figure out how to give user all the options for starting, stopping, and restarting program?

Ok so I am trying to build this random number teller which basically tells the users whether the number they input is less than, greater than, or equal to 50 and also give them the options to start, stop, and restart the "random number teller" Here is the code:
#include <iostream>
using namespace std;
main() {
cin >> boolalpha;
int invalid_answer {0};
const int const_num {50};
int random_num {};
char answer {};
int keep_going {};
while (keep_going == 0) {
while (invalid_answer == 0) {
//=======================================================================================================================================
cout << "Enter a random number and we will tell you if it is greater than or less than " << const_num << ": " << endl;
cin >> random_num;
if (random_num > const_num) {
cout << random_num << " is greater than " << const_num;
}
else if (random_num == const_num) {
cout << random_num << " is the same as " << const_num << endl;
}
else {
cout << random_num << " is less than " << const_num << endl;
}
cout << "Want to try again? Type \"Y\" or \"N\"";
cin >> answer;
//=======================================================================================================================================
if (answer == 'N') {
cout << "Ok then, sorry to see you miss out" << endl;
keep_going = 1;
}
//=======================================================================================================================================
while(answer == 'Y') {
cout << "Enter a random number and we will tell you if it is greater than or less than " << const_num << ": " << endl;
cin >> random_num;
if (random_num > const_num) {
cout << random_num << " is greater than " << const_num;
}
else if (random_num == const_num) {
cout << random_num << " is the same as " << const_num << endl;
}
else {
cout << random_num << " is less than " << const_num << endl;
}
cout << "\nWant to try again? Type \"Y\" or \"N\"";
cin >> answer;
}
//=======================================================================================================================================
if (answer != 'Y' || answer != 'N') {
invalid_answer = 1;
}
//=======================================================================================================================================
while (invalid_answer == 1) {
cout << "I'm sorry what? Please note that answers are case sensitive. Answer again: ";
cin >> answer;
if (answer == 'Y') {
invalid_answer = 0;
}
else if (answer == 'N') {
cout << "Ok then, sorry to see you miss out" << endl;
keep_going = 1;
}
}
}
}
}
Whenever I say "N" for No I don't want to redo the random number checker, it doesn't change keep_going to 1 it just moves on to one of the other if or while statements below it. So when you input "N" it just outputs either "Enter a random number and we will tell you if it is greater than or less than " << const_num << ": " or "I'm sorry what? Please note that answers are case sensitive. Answer again: "
The problem is with this bit of code:
if (answer != 'Y' || answer != 'N') {
invalid_answer = 1;
}
When answer is 'N', answer != 'Y' is true and invalid_answer is set to 1 (because of short-circuit evaluation the rhs of the logical OR is not even evaluated - see quote below).
So the execution will enter the while
while (invalid_answer == 1)
and will print the statements.
You can correct this by:
if (answer == 'Y' || answer == 'N') { //if input is either 'Y' or 'N'
invalid_answer = 0;
}
else { //for all other inputs
invalid_answer = 1;
}
Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first), but overloaded operators behave like regular function calls and always evaluate both operands
Also note that main should have the type int.
I figured it out right after I posted the question haha, basically the answer above was correct so I had to split that if statement into 2 others, in which I added an else statement to each also that said invalid_answer = 0; to make sure. But then after the user's second time using the program, if they wanted to quit it wouldn't let them and would just restart it again. I solved that by adding
if (answer == 'N') {
cout << "Ok then, sorry to see you miss out" << endl;
keep_going = 1;
}`
to the bottom of the while(answer == 'Y') loop.

Sentinel loop won't run

My program will compile but I'm running into a couple problems. My first cout statement requiring e/E to end works, but in my second while loop where I state (+ || - || * || /) won't run. +/-/*// returns "Operation type invalid". Can you guys help me see my error?
First sentinel loop, just learning loops:
#include <iostream>
using namespace std;
int main()
{
int numOne;
int numTwo;
int result;
string operation;
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
while (operation == "e" || "E")
{
cout << "Operation type invalid." << endl;
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
}
while (operation == "+" || operation == "-" || operation == "*" || operation == "/")
{
cout << "Please enter integer one: " << endl;
cin >> numOne;
cout << "Please enter integer two: " << endl;
cin >> numTwo;
if (operation == "+")
{
result = numOne + numTwo;
cout << "The numbers you entered were " << numOne << "," << numTwo << endl;
cout << "The operation you chose was " << operation << "." << endl;
cout << "The operations result is " << result << "." << endl;
cout << "Your equation was: " << numOne << " " << operation << " " << numTwo << " = " << result << ".";
}
else if (operation == "-")
{
result = numOne - numTwo;
cout << "The numbers you entered were " << numOne << "," << numTwo << endl;
cout << "The operation you chose was " << operation << "." << endl;
cout << "The operations result is " << result << "." << endl;
cout << "Your equation was: " << numOne << " " << operation << " " << numTwo << " = " << result << ".";
}
else if (operation == "*")
{
result = numOne * numTwo;
cout << "The numbers you entered were " << numOne << "," << numTwo << endl;
cout << "The operation you chose was " << operation << "." << endl;
cout << "The operations result is " << result << endl;
cout << "Your equation was: " << numOne << " " << operation << " " << numTwo << " = " << result << ".";
}
else if (operation == "/")
{
if (numTwo == 0)
{
cout << "You cannot divide by zero!" << endl;
}
else
{
result = numOne / numTwo;
cout << "The numbers you entered were " << numOne << "," << numTwo << endl;
cout << "The operation you chose was " << operation << "." << endl;
cout << "The operations result is " << result << endl;
cout << "Your equation was: " << numOne << " " << operation << " " << numTwo << " = " << result << ".";
}
}
}
return 0;
}
while (operation == "e" || "E")
Here you are comparing one of two conditions:
Does operation == "e"?
If not, is "E" a valid pointer?
That second condition is your problem: "E" is of course a valid pointer, so that condition will always be true. Always. Notice that in the second condition, you are not comparing operation to "E".
You are forever stuck here:
while (operation == "e" || "E")
{
cout << "Operation type invalid." << endl;
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
}
You simply need to have:
while (operation == "e" || operation == "E")
This is probably just a typo or an oversight more than anything else.

How do I loop to the top in C++? Could you show me an example?

I'm trying to make my calcuator loop back to the top after it finishes the calculation? I've tried while loops and seen tutorials on it but I just can't put it into context.
If you could show me how to actually use it in this program, that would be fantastic.
#include<iostream>
using namespace std;
int main() {
double num1, num2;
char op;
cout << "********C++ CALCULATOR********" << endl;
cout << "Please enter your first number" << endl;
cin >> num1;
cout << "Please enter your operand (+, -, *, /)\n" << endl;
cin >> op;
cout << "Please enter your second number\n" << endl;
cin >> num2;
if (op== '+') {
cout << "The answer is: " << num1 + num2 << endl;
} else if (op == '-') {
cout << "The answer is: " << num1 - num2 << endl;
} else if (op == '/') {
cout << "The answer is: " << num1 / num2 << endl;
} else if (op == '*') {
cout << "The answer is: " << num1 * num2 << endl;
} else {
cout << "That was an invalid command!" << endl;
}
}
I think you want anything like this:
#include<iostream>
using namespace std;
int main() {
double num1 = 0, num2 = 0;
char op = '';
char answer = '';
while(answer != 'n') { // Check condition
cout << "********C++ CALCULATOR********" << endl;
cout << "Please enter your first number" << endl;
cin >> num1;
cout << "Please enter your operand (+, -, *, /)" << endl;
cin >> op;
cout << "Please enter your second number\n" << endl;
cin >> num2;
if (op == '+') {
cout << "The answer is: " << num1 + num2 << endl;
} else if (op == '-') {
cout << "The answer is: " << num1 - num2 << endl;
} else if (op == '/') {
cout << "The answer is: " << num1 / num2 << endl;
} else if (op == '*') {
cout << "The answer is: " << num1 * num2 << endl;
} else {
cout << "That was an invalid command!\n Exit." << endl;
}
cout << "Do you want repeat? \"y\" or \"n\"\n" << endl;
cin >> answer;
}
}
The while construct consists of a block of code and a condition. The condition is evaluated, and if the condition is true, the code within the block is executed. This repeats until the condition becomes false. Because while loop checks the condition before the block is executed, the control structure is often also known as a pre-test loop. Compare with the do while loop, which tests the condition after the loop has executed.
For something that you want to run at least once you can also try a do/while statement.
In place of the word "do" you could use the 'while (again!='n');' at that loops lines curly brace (removing that "while again!='n';" check in the process) to have a standard while loop.
while(value==true) { ... }
as opposed to
do { ... } while(value==true);
This would require a properly initialized test variable though.
I included a second while loop in the larger do/while loop for further demonstration.
#include<iostream>
using namespace std;
int main() {
double num1 = 0, num2 = 0;
char op;
char again;
do { // set start point for loop
cout << "********C++ CALCULATOR********" << endl;
cout << "Please enter your first number" << endl;
cin >> num1;
cout << "Please enter your operand (+, -, *, /)" << endl;
cin >> op;
cout << "Please enter your second number" << endl;
cin >> num2;
if (op == '+') {
cout << "The answer is: " << num1 + num2 << endl;
} else if (op == '-') {
cout << "The answer is: " << num1 - num2 << endl;
} else if (op == '/') {
cout << "The answer is: " << num1 / num2 << endl;
} else if (op == '*') {
cout << "The answer is: " << num1 * num2 << endl;
} else {
cout << "That was an invalid command!" << endl;
}
cout << "\nRun again? \"y\" or \"n\"" << endl; // prompt user
cin >> again;
// here is a while loop in do/while statement to check for valid input if the user wants
// to go again
while(again!='y' && again!='n'){
cout << "Invalid input. Run again? y or n" << endl;
cin >> again;
}
cout << endl;
} while(again!='n'); // now check if user wants to go again // end of do loop
// the condition for while loop could be like
// while (1); // any non zero being true
// if you want executions until program termination
}
}
Just wrap everything into an endless loop
#include<iostream>
using namespace std;
int main() {
for (;;) {
// your code here
}
}

C++ Constant char

I built a simple calculator out of c++, it uses chars, so (+,-*,/) will works as math operators but when a user inputs an '=' it does't work.
#include <iostream>
#include <string>
#include <sstream>
#include <math.h>
using namespace std;
#define PI 3.14159265359
#define NEWLINE '\n'
void printf(string string)
{
cout << string;
}
int main ()
{
char operation;
double a,b,c, value;
double answer = 0;
bool more = true;
cout << "Welcome to My Calculator\n\nInput a value: ";
cin >> answer;
operations:
cin >> operation;
if (operation != '=') {
if (operation == '+') {
cin >> value;
cout << "\n" << answer << " " << operation << " " << value << "\n";
answer += value;
cout << "Equals " << answer << "\n";
cout << answer << " - New Operation? ";
goto operations;
}
if (operation == '-') {
cin >> value;
cout << "\n" << answer << " " << operation << " " << value << "\n";
answer -= value;
cout << "Equals " << answer << "\n";
cout << answer << " - New Operation? ";
goto operations;
}
if (operation == '*') {
cin >> value;
cout << "\n" << answer << " " << operation << " " << value << "\n";
answer *= value;
cout << "Equals " << answer << "\n\n";
cout << answer << " - New Operation? ";
goto operations;
}
if (operation == '/') {
cin >> value;
cout << "\n" << answer << " " << operation << " " << value << "\n";
answer /= value;
cout << "Equals " << answer << "\n\n";
cout << answer << " - New Operation? ";
goto operations;
}
if (operation == '^') {
cin >> value;
cout << "\n" << answer << " " << operation << " " << value << "\n";
answer = pow(answer, value);
cout << "Equals " << answer << "\n\n";
cout << answer << " - New Operation? ";
goto operations;
}
if (operation == '=') {
cout << "\nFinal Answer = " << answer << "\n\nNew operation [yes/no]: ";
string check;
cin >> check;
if (check == "yes") {
cout << "\nInput value: ";
cin >> answer;
cout << "\n";
goto operations;
} else {
cout << "\nGoodbye for now...\n";
return 0;
}
}
} else {
cout << "Unknown Error! Program Closing...";
return 0;
}
return 0;
}
When a user uses any operation besides = it works perfectly, but if I use and equals sign it doesn't work.
Example program out put:
Welcome to My Calculator
Input a value: 4
+4
4 + 4
Equals 8
8 - New Operation? - 3
8 - 3
Equals 5
5 - New Operation? * 5
5 * 5
Equals 25
25 - New Operation? /2
25 / 2
Equals 12.5
12.5 - New Operation? ^2
12.5 ^ 2
Equals 156.25
156.25 - New Operation? =
Unknown Error! Program Closing...
if (operation != '=') {
...
if (operation == '=') {
}
}
If operation isn't equal to "=" and if it's equal to "=". I think you planned to put a closure operator or something like that in the first outer if.
your statement if (operation != '=') causes the control to be transferred to the else statement
Because you have an if (operation != '=') outside the if checking for =. You don't want to do that.