I'm new to C++ programming.
I just want to know if there is any way to go back to a certain point in the code without using a while or a do-while loop.
Here is an example:
int a;
cout << "What's 2+2?";
cin >> a;
if (a==4) {cout << "Nice!";}
else {cout << "WRONG! Try again!";}
So, if the player fails, I want to ask the question again, so going back to:
cout << "What's 2+2?";
Is there any way to do it without using a loop?
You want to repeat something until a condition is satisfied. That is the definition of a loop, and there are many ways to write loops in C++. The example you showed is best handled using a do-while loop:
int a;
do
{
cout << "What's 2+2?";
cin >> a;
if (a == 4) {
cout << "Nice!";
break;
}
cout << "WRONG! Try again!";
}
while (true);
Though you could use a while or for loop instead:
int a;
while (true)
{
cout << "What's 2+2?";
cin >> a;
if (a == 4) {
cout << "Nice!";
break;
}
cout << "WRONG! Try again!";
}
int a;
for(;;)
{
cout << "What's 2+2?";
cin >> a;
if (a == 4) {
cout << "Nice!";
break;
}
cout << "WRONG! Try again!";
}
That being said, to answer your actual question, you can use a goto statement without any other looping instructions:
int a;
askTheUser:
cout << "What's 2+2?";
cin >> a;
if (a != 4) {
cout << "WRONG! Try again!";
goto askTheUser;
}
cout << "Nice!";
But, goto is rarely used in modern coding, it is not likely to perform any better than a do-while loop after compiler optimizations are applied, and it has limitations on how it can be used.
The preferred language construct for executing a block of code more than once is a loop, which can be of a for, a do-while, or a while form.
So I'd write the code as follows:
int a;
bool correctGuess = false;
while (!correctGuess) {
cout << "What's 2+2?";
cin >> a;
if (a==4) {cout << "Nice!"; correctGuess = true; }
else { cout << "WRONG! Try again!"; }
}
Another way would be the use of recursion, i.e. a function that calls itself until a particular condition is met. Yet this seems to be a to complicated approach for your scenario.
If - for any reason - you are asked to not use such kind of loops, you could use a goto-statement (though this is clearly not the preferred way to do; goto-statements are very rarely used nowadays):
int a;
loop:
cout << "What's 2+2?";
cin >> a;
if (a==4) {cout << "Nice!";}
else {
cout << "WRONG! Try again!";
goto loop;
}
DontDoThis:
...
goto DontDoThis;
That's it.
DontDoThis: is a "label", and goto DontDoThis jumps execution to the specified label. But, like the label's name says, DONT DO THIS! Using goto is concerned bad practice in modern coding, there are better ways to handle looping.
You should initialize a to 0 and then use a while (a != 4) loop. But that's not your question :)
The other loop statement is for
Another way is to use functions - they can be called repeatedly.
Well, if you don't want to use a while or do-while...
for (;;) //same as while(true)
{
int a;
cout << "What's 2+2?";
cin >> a;
if (a==4)
{
cout << "Nice!";
break;
}
else
{
cout << "WRONG! Try again!";
}
}
Related
I've started to learn how to code in C++ on my spare time, using different sites and apps that someone who has also learned C++ online provided me with. By now, I know the most basic commands. I've tried an exercise given by a program, and I'm given the information that someone is going on a vacation, and needs to know how much baggage he can bring with him. The limit to how many baggages he can carry is 45, and I have to display a different output if the baggages are below, above or the same as the limit (45 baggages). I have done some coding, and I ended up with this:
#include <iostream>
using namespace std;
int main()
{
const int limit = 45;
int bag;
cout << "Please type your number here: ";
cin >> bag;
string yn;
int keep = 0;
if (limit < bag)
{
cout << "You passed the limit." << endl;
};
if (limit == bag)
{
cout << "Just enough." << endl;
};
if (limit > bag)
{
cout << "You got space." << endl;
};
++keep;
while(keep > 0)
{
int keep = 0;
cout << "Do you want to try another number?" << endl;
cin >> yn;
cout << endl;
if(yn == "yes")
{
int bag = 0;
cout << "Please type your number here: ";
cin >> bag;
if (limit < bag)
{
cout << "You passed the limit." << endl;
};
if (limit == bag)
{
cout << "Just enough." << endl;
};
if (limit > bag)
{
cout << "You got space." << endl;
};
}
else
{
return 0;
}
}
}
I have developed it more than needed -as you can see-, out of my own interest in the problem. I have copied and pasted the 3 IF commands as seen above, and I believe that there is an easier way, with less code, do solve this. What I have thought of is if I could go back and execute some line of code again, either from a line and below (e.g. from line 45 and below), or specific lines of code (e.g. from line 45 to line 60).
I would appreciate it if you thought of another way to solve this problem and posted your code below.
Thank you for your reply.
We all started writing our first C++ program at some time, so allow me to give you some additional feedback:
First of all, avoid writing using namespace std;
Secondly, naming - what is bag, limit, keep and yn? Wouldn't it be much easier to read and understand if they were called bagSize, maximumPermittedBagSize, inputFromUser (you don't really need the variable keep, see below)?
Finally, here is a (roughly) refactored version your program, with duplication removed and comments added.
#include <iostream>
int main()
{
const int maximumPermittedBagSize = 45;
// Loops forever, the user exits by typing anything except 'yes' laster
while(true)
{
std::cout << "Please type your number here: " << std::endl;
//Declare (and initialize!) variables just before you need them
int bagSize = 0;
std::cin >> bagSize;
if (bagSize > maximumPermittedBagSize)
{
std::cout << "You passed the limit." << std::endl;
}
else if (bagSize == maximumPermittedBagSize )
{
std::cout << "Just enough." << std::endl;
}
else
{
std::cout << "You got space." << std::endl;
}
std::cout << "Do you want to try another number?" << std::endl;
std::string inputFromUser = "";
std::cin >> inputFromUser;
std::cout << std::endl;
//Leave the loop if the user does not answer yes
if(inputFromUser != "yes")
{
return 0;
}
}
}
You can simply run a while loop and do like this:
#include <iostream>
using namespace std;
int main()
{
const int limit = 45;
int bag;
string yn = "yes";
while(yn == "yes")
{
cout << "Please type your number here: ";
cin >> bag;
if (limit < bag)
{
cout << "You passed the limit." << endl;
}
else if (limit == bag)
{
cout << "Just enough." << endl;
}
else if (limit > bag)
{
cout << "You got space." << endl;
}
cout << "Do you want to try another number?" << endl;
cin >> yn;
cout << endl;
}
}
#include <iostream>
#include "funktionen.h"
using namespace std;
int rechnung()
{
cout << "Please choose the operator you want to calculate with" << endl;
int eingabe1;
int eingabe2;
int eingabe;
int dummy;
char zeichen;
char again;
cin >> zeichen;
cout << endl << "1. Eingabe: ";
cin >> eingabe1;
cout << endl << "2. Eingabe: ";
cin >> eingabe2;
switch (zeichen)
{
case '+':
eingabe=eingabe1 + eingabe2;
break;
case '-':
eingabe=eingabe1 - eingabe2;
break;
case '*':
eingabe=eingabe1 * eingabe2;
break;
case '/':
eingabe=eingabe1 / eingabe2;
break;
}
cout << endl << "Das Ergebnis ist | " << eingabe << " | " << endl << endl;
cout << "Wanna calculate again? ";
cin >> again;
while(again=='Y')
{
rechnung();
}
return 0;
}
So this is my code in an implementation file. My problem is, that the main program always loops the whole "rechnung()" function even though I don't type "Y" into the console once it asks for it. In the beginning, when I type something else than "Y", then the console closes (as it shall) but if I do a calculation, type "Y", do another calculation and type "k" for example, it also starts from the beginning of "rechnung()". Why does it do so? I mean I told him that he shall only recall the "rechnung()" if the character input is "Y".
Consider this maybe simpler example:
void foo() {}
void bar() {
char again;
// ... do something
std::cin >> again;
while(again=='Y') {
foo();
}
}
Inside the loop the value of again never changes, so there is an infinite loop. However, your code goes one step further by calling the function recursively. Strongly simplified you have:
void bar() {
// .. do something
while (true) {
bar();
}
}
ie bar is calling itself again and again and never returns. You put the loop at the wrong place. You could write it like this
void bar() {
char again = 'Y';
while (again == 'Y') {
// .. do something
std::cout << "repeat?";
std::cin >> again;
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
#include <iostream>
using namespace std;
int main()
{
float a, b, result;
char operation, response;
cin >> a >> operation >> b;
switch(operation)
{
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
default:
cout << "Invalid operation. Program terminated." << endl;
return -1;
}
// Output result
cout << "The result is " << result << endl;
system("sleep 200");
cout << "Do you want to make another opertaion? (Y/N)" << endl;
cin >> response;
if(response=='Y')
{
here
}
else if(response=='N')
{
cout << "The program will now close" << endl;
system("sleep 500");
return -1;
}
return 0;
}
Where the word 'here' is written, I want to insert a code that gets you to the beggining of the code.
You can use the loop do... while(condition)
Like :
do{
cin >> a >> operation >> b;
switch(operation)
{
...
}
// Output result
cout << "The result is " << result << endl;
system("sleep 200");
cout << "Do you want to make another opertaion? (Y/N)" << endl;
cin >> response;
}while(response=='Y');
If the response isn't 'Y' the loop ends, if it is the loop begin again
All though goto is highly frowned upon in C++, it does exist.
Much like assembly, your put a label in your code and then tell it to 'jump' there using goto. However, the same way jump works in assembly, this may break you out of all loops to the point that you jump to.
#include <iostream>
using namespace std;
int main()
{
label:
float a, b, result;
char operation, response;
cin >> a >> operation >> b;
//condensed for neatness
// Output result
cout << "The result is " << result << endl;
system("sleep 200");
cout << "Do you want to make another opertaion? (Y/N)" << endl;
cin >> response;
if(response=='Y')
{
goto label;
}
else if(response=='N')
{
cout << "The program will no`enter code here`w close" << endl;
system("sleep 500");
return -1;
}
return 0;
}
What most people would do is use a do{}while(condition==true) loop or just an infinite loop while(true).
For this 'neater' code, what you would do is
#include <iostream>
using namespace std;
int main()
{
do{
float a, b, result;
char operation, response;
cin >> a >> operation >> b;
//condensed for neatness
// Output result
cout << "The result is " << result << endl;
system("sleep 200");
cout << "Do you want to make another opertaion? (Y/N)" << endl;
}while(cin.get() == 'Y');
cout << "The program will no`enter code here`w close" << endl;
system("sleep 500");
return -1;
return 0;
}
If this is being called from another location, I would highly recommend using do while rather than goto, as it can cause issues.
The only real problem with goto is that it's not elegant and makes code confusing to read. You should use loops and returns where possible, and only use goto if you see no other way to make this work optimally.
int guess_number = (gen() % 1000);
cout << guess_number;
int number = 0;
cout << "Number:";
cin >> number;
do
{
if (number>guess_number)
{
cout << "Too High"<<"\n";
cin >> number;
}
else if (number<guess_number)
{
cout << "Too Low"<< "\n";
cin >> number;
}
} while (number != guess_number);
int again=0;
cout << "Wanna Play Again!";
cin >> again;
I'm making a guessing game, but must loop the game if the player answers 1 after "Wanna Play Again!" I'am working with if,for,do, switch, and while statements. Its an assignment I was given and I just can't seem to figure out exactly how to loop the entier statement. I have made several attempts, but it either exits the program or continually prints "Wanna Play Again!".
How about wrapping the existing do/while with a another for the play again condition ?
int again =0;
do{
do{
//existing code
} //end inner while
cout << "Wanna Play Again?";
cin >> again;
} while(again != 0); //or whatever makes sense for the condition
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Made my first C++ program ever. A basic calculator.
Got stuck at this part where I was suppose to make the program repeat.
So at "Point A" you select if you want to count division/addition etc. and it takes you there. When you run it once, it asks if you want to repeat the function (e.g division) or go back to the "Point A" (you just type y[yes] (repeats the division) or n[no](goes to "point A")).
I'm new to C++, haven't got really familiar with loops yet.
Also the code structures make my head spin, so Google didn't help me much.
I've heard about the "goto" function (or whatever you call it) but I was told that i shouldn't be used in this case.
Take a look. The texts, and most of the comments are in Finnish, but I hope you'll get the point from English comments.
#include <iostream>
using namespace std;
float addition(float num1, float num2)
{
return num1 + num2;
}
float substraction(float num1, float num2)
{
return num1 - num2;
}
float multiplication(float num1, float num2)
{
return num1 * num2;
}
float division(float num1, float num2)
{
return num1 / num2;
}
//This function should throw you back to point 'A'
int valinta2{
while (valinta2 == y){
}
}
int main(void)
{
//Point A
float number1;
float number2;
int valinta;
cout << "\n-*-*-*-*-*-*-*-*-*-*\nClaudion Laskin\n-*-*-*-*-*-*-*-*-*-*";
//Select what you want to count
cout << "\n\n\nValitse mita haluat laskea. \n\nVaihtoehdot: " << endl;
cout << "1. Plus-laskut\n 2. Vahennys-laskut\n 3. Kerto-laskut\n 4. Jako-laskut \n\nValinta: ";
cin >> valinta;
if (valinta == 1){
//Addition
cout << "\n\n\n===============\n||Plus laskut||\n=============== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n+\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << addition(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cin.get();
}
else {
if (valinta == 2){
//Subtraction
cout << "\n\n\n===================\n||Vahennys laskut||\n=================== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n-\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << substraction(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cout << "Valinta: ";
cin >> valinta2;
}
else {
if (valinta == 3){
//Multiplication
cout << "\n\n\n================\n||Kerto laskut||\n================ \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n*\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << multiplication(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cin.get();
}
else {
if (valinta == 4){
//Division
cout << "\n\n\n===============\n||Jako laskut||\n=============== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n/\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << division(number1, number2) << "\n----------\n" << endl;
}
}
}
}
system("pause");
return 0;
}
You need to restructure your code to include the while loop in the main method. There would be ways to "go to" your "Point A", but they are messy and shouldn't be used (goto is the keyword here).
So at "Point A", insert
do {
float number1;
// ...
and then down at where you would like to call valinta2 (notice that you don't even call the function at the moment - I'm guessing it would have to be just before the call to system("pause")), do the check of the condition, like so:
} while (...);
And best revisit the chapter on flow control/loops in the C++ tutorial of your choice, e.g. one of those mentioned here: The Definitive C++ Book Guide and List
Alternative to nyarlathotep's perfectly good answer, one method I like using follows this form:
while(true) {
//do stuff
//then when ready to check for exit condition
if(exitCondition == true) { //the ==true part is redundant
break;
}
//do more stuff
//if you need to go to the beginning of the loop and
//skip any code following a point, do this:
if(skipRestOfLoopCondition) {
continue;
}
//you can always check other exit conditions or check
//the same one at multiple places
if(someOtherExitCondition) {
break;
}
//do even more stuff
}
system("pause");
return 0;
As a caveat, you must provide a way for at least one of the if's that result in break; to actually execute, because while(true) loop condition never gets you out of the loop, you can only get out of the loop with a break;.
I am pretty new to this and I don't know if I am right. I can hardly understand your code. However, when I am programming in c for the arduino and I want my code to loop forever I just put
void loop() {// my code follows from here