How do I loop back to the beginning in c++ - c++

I recently started programming in C++, so for my program I need to loop back to the beginning when the user says yes and end the program when the user says no. I was wondering how would I loop back to the beginning?
#include <iostream>
using namespace std;
int main() {
int x;
int y;
char yes, no, answer;
{
cout << "Please enter a number for the x coordinate" << endl;
cin >> x;
cout << "Please enter a number for the y coordinate" << endl;
cin >> y;
if (x == 0) {
if (y == 0)
cout << "you are on the origin" << endl;
else
cout << "you are on the y axis" << endl;
}
else if (x > 0) {
if (y == 0)
cout << "you are on the x coordinate" << endl;
else if (y > 0)
cout << "you are in the 1st quadrant" << endl;
else
cout << "you are in the 4th qaudrant" << endl;
}
else if (x < 0) {
if (y > 0)
cout << "you are in the 2nd quadrant" << endl;
else if (y < 0)
cout << "you are in the 3rd quadrant" << endl;
}
cout << "Do you want to run the program again either types yes or no" << endl;
cin >> answer;
if (answer == 'yes' || answer == 'Yes')
system("pause");
}
}

You can put the code inside a loop:
while(true) {
... (existing code goes here)
if (answer != 'yes' && answer != 'Yes')
break;
}

Related

Why is my loop not restarting to the first iteration? C++

I'm making a Dice Game in C++. I was wondering why it doesn't restart the loop. The game is Best of 3. It's supposed to restart the loop as long as the player wants to keep playing. However it only restarts the loop once. The second time I press 'Y' or yes in this case it just exits the program.
I've tried putting the restart in a nested while loop but it doesn't seem to work either.
restart:
while ((pWin != 2) && (cWin != 2))
{
pDice1 = rand() % 6 + 1;
cDice1 = rand() % 6 + 1;
cout << "Player score is: " << pDice1 << endl;
cout << "Computer score is: " << cDice1 << endl;
if (cDice1 > pDice1) {
cout << "Computer wins!" << endl << endl;
cWin++;
} if (pDice1 > cDice1) {
cout << "Player wins!" << endl << endl;
pWin++;
} if (pDice1 == cDice1) {
cout << "It's a draw!" << endl << endl;
} if (pWin > cWin) {
cout << "Player wins this round! Do you wish to keep playing?" << endl;
cin >> Y;
if (Y == 'y') {
goto restart;
}
else {
exit(0);
}
}if (cWin > pWin) {
cout << "Computer wins this round! Do you wish to keep playing?" << endl;
cin >> Y;
if (Y == 'y') {
goto restart;
}
else {
exit(0);
}
}
}
First, is this all your code? I noticed most of your variables seem to be declared outside of the provided code block. If so, is your "Y" being declared as a char and not a string type to match your condition type?
It looks like you are failing to set your pWin and cWin back to zero when it returns to the top. You can fix with:
restart:
cWin = 0;
pWin = 0;
while ((pWin != 2) && (cWin != 2))
{
pDice1 = rand() % 6 + 1;
cDice1 = rand() % 6 + 1;
cout << "Player score is: " << pDice1 << endl;
cout << "Computer score is: " << cDice1 << endl;
if (cDice1 > pDice1) {
cout << "Computer wins!" << endl << endl;
cWin++;
} if (pDice1 > cDice1) {
cout << "Player wins!" << endl << endl;
pWin++;
} if (pDice1 == cDice1) {
cout << "It's a draw!" << endl << endl;
} if (pWin > cWin) {
cout << "Player wins this round! Do you wish to keep playing?" << endl;
cin >> Y;
if (Y == 'y') {
goto restart;
}
else {
exit(0);
}
}if (cWin > pWin) {
cout << "Computer wins this round! Do you wish to keep playing?" << endl;
cin >> Y;
if (Y == 'y') {
goto restart;
}
else {
exit(0);
}
}
}
Because you don't reset pWin and cWin to zero after a game.
You should fix that but also turn the goto into another while loop and make the guts of that while loop into a function maybe.

Nested IF Statement C++ Syntax

Is my syntax correct for this nested if statement?
I am trying to run through all values. But it does not seem to provide any outputs is all values are not equal to 1.
I am using Xcode so some of the code may differ than in VS.
#include <iostream>
using namespace std;
int main() {
int haveMoney, haveTime, amHungry, restaurantOpen, haveTransportation;
cout << "Yes = 1, 2 = No" << endl << endl;
cout << "Do I have money?" << endl;
cin >> haveMoney;
cout << "Do I have time?" << endl;
cin >> haveTime;
cout << "Am I hungry?" << endl;
cin >> amHungry;
cout << "Are they open?" << endl;
cin >> restaurantOpen;
cout << "Do I have transportation?"<< endl;
cin >> haveTransportation;
if ((haveMoney == 1) && (haveTime == 1) && (amHungry == 1) && (restaurantOpen == 1) && (haveTransportation == 1)){
cout << "Enjoy your McDonalds!" << endl << endl;
if (haveMoney == 2){
cout << "You're broke, so you can't have McDonalds" << endl ;
if (haveTime == 2){
cout << "You don't have enough time to go to McDonalds!" << endl ;
if (amHungry == 2){
cout << "Why are you even thinking about McDonalds, you're not hungry!" << endl ;
if (restaurantOpen == 2){
cout << "McDonalds is closed, tough luck." << endl ;
if (haveTransportation == 2){
cout << "You have no transportation to get to McDonalds." << endl ;
}
}
}
}
}
}
return 0;
}
You need chained if-else-if statements, not nested if statements. This does what you expect. Note that I have omitted the curly braces for the if statements for ease of typing.
#include <iostream>
using namespace std;
int main() {
int haveMoney, haveTime, amHungry, restaurantOpen, haveTransportation;
cout << "Yes = 1, 2 = No" << endl << endl;
cout << "Do I have money?" << endl;
cin >> haveMoney;
cout << "Do I have time?" << endl;
cin >> haveTime;
cout << "Am I hungry?" << endl;
cin >> amHungry;
cout << "Are they open?" << endl;
cin >> restaurantOpen;
cout << "Do I have transportation?"<< endl;
cin >> haveTransportation;
if ((haveMoney == 1) && (haveTime == 1) && (amHungry == 1) && (restaurantOpen == 1) && (haveTransportation == 1))
cout << "Enjoy your McDonalds!" << endl << endl;
else if (haveMoney == 2)
cout << "You're broke, so you can't have McDonalds" << endl ;
else if (haveTime == 2)
cout << "You don't have enough time to go to McDonalds!" << endl ;
else if (amHungry == 2)
cout << "Why are you even thinking about McDonalds, you're not hungry!" << endl ;
else if (restaurantOpen == 2)
cout << "McDonalds is closed, tough luck." << endl ;
else if (haveTransportation == 2)
cout << "You have no transportation to get to McDonalds." << endl ;
return 0;
}

Asking the user to input one of the options and depending on the choice, the program shows the answer

How to ask the user to input two numbers, and after that show these options:
sum,
average,
maximum,
minimum,
exit.
Then due to the user choice, the program shows the answer, and this process continues until the user input number 5.
My code does not work properly. Here is the code:
#include <stdio.h>
#include <iostream>
using namespace std;
int main() {
int x, y, choice;
char sum, average, max, min;
cout << "Enter two numbers: " << endl;
cin >> x >> y;
cout << "Choose one of these options: \n";
cout << " sum - average - max - min - exit " << endl;
choice == sum || average || max || min;
cin >> choice;
sum == x + y;
max == x > y || y > x;
if (choice == sum) {
cout << "The sum is: " << x + y << endl;
}
if (choice == average) {
cout << "The average is: " << x / y << endl;
}
if (choice == max&& x > y) {
cout << "The maximum is: " << x << endl;
} else
cout << " The maximum is: " << y << endl;
if (choice == min&& x < y) {
cout << "The minimun is: " << x << endl;
} else
cout << " The minimun is: " << y << endl;
while (true) {
string choice;
cin >> choice;
if (choice == "5") {
break;
}
}
return 0;
}
So you want to calculator which should end based on the user choice? If So
You can wrap the Function with a While loop and Keep a set a bool based on the user input. Like :
bool Terminate = false;
while(!Terminate)
{
//Do Your Calculations Here
//Ask for the User Input
std::string UserChoice = "";
std::cout << "Do You Want to Exit [ Y/N ]";
std::cin << UserChoice;
if(UserChoice == "Y" || USerChoice == "y")
{
std::cout << "Ending the Program";
Terminate = true;
}
}
If you have any doubts check this out
https://learn.microsoft.com/en-us/cpp/get-started/tutorial-console-cpp?view=msvc-160

How to make cin accept a single digit only c++

So we were challenged by a teacher to make this simple game into a c++ program.
English is not my primary language but I'll try to explain. I'm a beginner so these will not be efficient, but I'm still proud of what I did so far.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int secret[3], i = 0, x, y, z, a, b, c, guess = 1, tries = 9;
bool correct = false;
srand(time(0));
do
{
secret[i] = rand() % 10;
i++;
} while (i <= 2);
x = secret[0];
y = secret[1];
z = secret[2];
//cout << x << y << z << endl; <--- for debugging purposes
cout << "=================================================\n\n";
cout << " I HAVE THREE SINGLE DIGIT NUMBERS\n\n";
cout << " YOU HAVE TEN TRIES TO GUESS ALL THREE DIGITS\n\n";
cout << "=================================================\n\n";
do
{
cout << "\n\nGuess the first digit.\n";
while (!(cin >> a))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please try again: \n";
}
cout << "\n\nGuess the second digit.\n";
cout << a;
while (!(cin >> b))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please try again: \n" << a;
}
cout << "\n\nGuess the third digit.\n";
cout << a << b;
while (!(cin >> c))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please try again: \n" << a << b;
}
cout << "\n\n====================================================\n\n";
if (tries == 0)
{
cout << "YOU RAN OUT OF GUESSES! \n";
cout << "The secret number is " << x << y << z << "!\n";
cout << "PLEASE RESTART THE PROGRAM TO TRY AGAIN!\n";
correct = true;
}
else if ((a == x) && (b == y) && (c == z))
{
cout << "YOU GUESSED THE SECRET NUMBER IN " << guess << " TRY / TRIES!\n";
cout << "CONGRATULATIONS!\n\n";
correct = true;
}
else if ((a == x) && (b == y) && (c != z))
{
cout << "You guessed TWO of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else if ((a == x) && (b != y) && (c != z))
{
cout << "You guessed ONE of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else if ((a == x) && (b != y) && (c == z))
{
cout << "You guessed TWO of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else if ((a != x) && (b == y) && (c == z))
{
cout << "You guessed TWO of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else if ((a != x) && (b == y) && (c != z))
{
cout << "You guessed ONE of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else if ((a != x) && (b != y) && (c == z))
{
cout << "You guessed ONE of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else
{
cout << "You guessed NONE of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
cout << "\n====================================================\n\n";
guess++;
tries--;
} while (correct == false);
}
I have a little problem though, in this part of the program,
cout << "\n\nGuess the first digit.\n";
while (!(cin >> a))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please try again: \n";
}
I could enter anything invalid and it will properly identify it as an invalid input. But if I enter 2 digits (22 for example), the program still enters 22 and it just accepts it.
I don't know exactly how that part of my program works, I just copy-pasted it. Is it possible to modify it, or my program to only accept a single digit, 0-9, and identify the input as invalid when two numbers are entered?
I know it's just a minor inconvenience and doesn't really break the program, but if I can make it better then it would be great. I just want it to be perfect, if possible.
I'm guessing if there's something like _getche for integers then it would be better?
Thanks in advance.
while (!(cin >> a)) means keep looping while not able to convert the input to an integer value in a - you can add extra conditions:
while (!(cin >> a) || a < 0 || a > 9)
In those latter cases, there's no need to .clear() and .ignore(...) but it won't do any harm.
In case it's new to you, || means logical-or, the equivalent logic to English such as: "a is less than 0 OR a is greater than 9".

C++ do-while loop won't quit even once the condition is met [duplicate]

This question already has answers here:
conditional statement in while loop
(2 answers)
std::cin of char causing infinite loop
(3 answers)
Closed 9 years ago.
So most of my program works fine. It is a program designed to estimate sine and cosine values using Taylor series. The program is designed to quit once the user inputs 0, and then "Y" or "y" upon being asked if they are sure. The char variable exit is initialized to "n", and then is changed if the user inputs y. But the loop doesn't quit then.
#include <iostream>
#include <cmath>
using namespace std;
double calculateFACT(int n); // function that calculates the factorial
double calculateSIN(float, float); // function that approximates the sine
double calculateCOS(float, float); // function that approximates the cosine
int main()
{
int choice; // menu choice
double angle = 0; // angle user inputs, initialied to zero
double calc; // the calculated sine or cosine value
int order; // order approimation value
char exit = 'n'; // exits for yes
do {
cout << "MAIN MENU" << endl;
cout << "1. To enter the data." << endl;
cout << "2. To calculate the sin(x)" << endl;
cout << "3. To approximate the sin(x)" << endl;
cout << "4. To calculate the cos(x)" << endl;
cout << "5. To approximate the cos(x)" << endl;
cout << "6. To re-enter data." << endl;
cout << "Press 0 to quit." << endl;
cout << "Please make a choice: ";
cin >> choice;
cout << endl;
if (choice != 0 &&
choice != 1 &&
choice != 2 &&
choice != 3 &&
choice != 4 &&
choice != 5 &&
choice != 6)
{
cout << "Wrong Choice. Only options 1-6 are available." << endl << endl;
}
if (choice == 1)
{
if (angle == 0)
{
cout << "Please give a value for the angle: ";
cin >> angle;
cout << endl;
}
else cout << "Please use option 6 to enter a new angle." << endl << endl;
}
if (choice == 2)
{
if (angle == 0)
{
cout << "You have to enter a value first!" << endl << endl;
}
else
{
calc = sin(angle);
cout << "The sine of x is " << calc << endl << endl << endl;
}
}
if (choice == 3)
{
if (angle == 0)
{
cout << "You have to enter a value first!" << endl << endl;
}
else
{
cout << "Please give a value for the approximation order n: ";
cin >> order;
cout << "The approximation of sin(" << angle << ") is: " << calculateSIN(angle, order) << endl << endl;
}
}
if (choice == 4)
{
if (angle == 0)
{
cout << "You have to enter a value first!" << endl << endl;
}
else
{
calc = cos(angle);
cout << "The cosine of x is " << calc << endl << endl << endl;
}
}
if (choice == 5)
{
if (angle == 0)
{
cout << "You have to enter a value first!" << endl << endl; // cosine function not giving the right value
}
else
{
cout << "Please give a value for the approximation order n: ";
cin >> order;
cout << "The approximation of cos(" << angle << ") is: " << calculateCOS(angle, order) << endl << endl;
}
}
if (choice == 6)
{
if (angle == 0)
{
cout << "If this is the first time you run this program please choose option 1." << endl << endl;
}
else
{
cout << "Please give new angle: ";
cin >> angle;
cout << endl << endl;
}
}
if (choice == 0)
{
cout << exit;
cout << endl << endl << "Are you sure you want to quit? (Y/N): "; // Y/N option doesnt work
cin >> exit;
}
cout << exit;
} while (exit != 'Y' || exit != 'y');
if (exit == 'Y' || exit == 'y')
{
cout << endl << "Now quitting.." << endl;
system("pause");
return 0;
}
}
double calculateFACT(int n)
{
double nfact = 1;
for (int i = 2; i <= n; i++)
nfact *= i;
return nfact;
}
double calculateSIN(float angle, float order)
{
double sine = angle;
for (int i = 1; i < order; i++)
{
sine += pow(-1.0, i) * (pow(angle, 2 * i + 1)) / calculateFACT(2 * i + 1);
}
return sine;
}
double calculateCOS(float angle, float order)
{
double cosine = 0;
for (int i = 0; i < order; i++)
{
cosine += pow(-1.0, i) * (pow(angle, 2 * i)) / calculateFACT(2 * i);
}
return cosine;
}
I answered a similar question named Why is my c++ code not working properly?. And the answer is exactly the same. You need to do exit != 'Y' && exit != 'y' otherwise it will always evaluate to true.
remyabel answered the question. Your code says "if the user didn't type 'Y' or 'y'", keep running. Since you're only looking for one character, it will keep running forever, since the character cannot be both 'Y' and 'y' at the same time.
Hence, while (exit != 'Y' && exit != 'y') essentially says "if the user didn't type an exit condition, I'm going to keep executing."