How to find out why my program keeps having an infinite loop? - c++

I can't seem to find what's wrong with my code, I'm trying to end the loop once the answers is equals to 0 but it keeps going on an infinite loop.
#include <iostream>
int main() {
using namespace std;
int x, remainder;
cout << "please enter a positive integer number: " << endl;
string tab;
tab = '\t';
cin >> x;
remainder = x % 2;
do{
while ( x % 2 != 0)
{
cout << x << " is odd" << tab << "Subtract 1" << tab << " Half of " << x - 1 << " is " << x / 2;
x = (x - 1) / 2;
cout << endl;
}
while (x % 2 == 0)
{
cout << x << " is even" << tab << "Subtract 0" << tab << "Half of " << x << " is " << x / 2;
x = x / 2;
cout << endl;
}
}
while (x >= 0);
}

There are, essentially, two problems in your code, both of which, in themselves, will make your loop run endlessly.
Starting from the outside and working inwards: The test at the end of your (outer) while loop will always be "true", as you have while (x >= 0); so, even when x gets to zero (as it will), the loop will keep running! (And, once x is zero it will remain zero!)
Second, the two 'inner' while loops shouldn't be loops at all! You want one or the other 'block' to run once only for each main loop - so use an if ... else structure.
The following is a corrected version of your code:
#include <iostream>
int main() {
// using namespace std; // Generally, not good practice (and frowned-upon here on SO)
using std::cin; using std::cout; using std::endl; // Use only those you want to!
using std::string;
int x, remainder;
cout << "please enter a positive integer number: " << endl;
string tab;
tab = '\t';
cin >> x;
remainder = x % 2;
do {
if (x % 2 != 0)
{
cout << x << " is odd" << tab << "Subtract 1" << tab << " Half of " << x - 1 << " is " << x / 2;
x = (x - 1) / 2;
cout << endl;
}
else // if (x % 2 == 0) ... but we don't need to test this again.
{
cout << x << " is even" << tab << "Subtract 0" << tab << "Half of " << x << " is " << x / 2;
x = x / 2;
cout << endl;
}
} while (x > 0); // You run forever if you have x >= 0!
return 0;
}
There are a few other things that could be changed to make the code more "efficient," but I'll let you peruse the MNC (Minimum Necessary Change) before we start editing towards a BPC (Best Possible Code)!
EDIT: OK, due to 'peer pressure' from comments 😊, I'll put in a suggested BPC now:
#include <iostream>
int main() {
using std::cin; using std::cout; using std::endl; // Use only those you want to!
int x;// , remainder; // "remainder" is never used, so we can discard it!
cout << "Please enter a positive integer number: " << endl;
cin >> x; // Not critical, but I like to put such a cin right after the prompting cout.
std::string tab{ "\t" }; // Let's initialise more directly!
do {
// As there is only one line (now) inside each if/else block, we can leave out the {} ...
if (x % 2 != 0)
cout << x << " is odd" << tab << "Subtract 1" << tab << "Half of " << x - 1 << " is " << x / 2;
else
cout << x << " is even" << tab << "Subtract 0" << tab << "Half of " << x << " is " << x / 2;
// We can put the following two line outside the tests, as they will be the same in both cases:
x = x / 2; // When x is ODD, this will give the SAME answer as x = (x - 1)/2 (as you noticed in your first cout)
cout << endl;
} while (x > 0); // You run forever if you have x >= 0!
return 0;
}

Related

How to print the and update the scoreboard on the same line here?

#include <iostream>
#include <cstdlib>
#include <iomanip>
int Human_Roll() {
int num1;
srand(time(0));
num1 = (1 + rand() % 6);
return num1;
}
int Human_Roll_2() {
int num2;
num2 = (1 + rand() % 6);
return num2;
}
int Computer_Roll() {
int num3;
num3 = (1 + rand() % 6);
return num3;
}
int Coumputer_Roll_2() {
int num4;
num4 = (1 + rand() % 6);
return num4;
}
int main() {
int counter1 = 0, counter2 = 0;
char start;
for (int i = 1; i <= 150; i++) {
std::cin >> start;
int x1{ Human_Roll() };
int x2{ Human_Roll_2() };
int y1{ Computer_Roll() };
int y2{ Coumputer_Roll_2() };
int x;
int y;
x = x1 + x2;
y = y1 + y2;
std::cout << "\nYou: " << x1 << " + " << x2 << " = " << x << "\n\n";
std::cout << "Computer: " << y1 << " + " << y2 << " = " << y << "\n";
if (x > y) {
std::cout << "\nYou win." << "\n";
++counter1;
}
if (y > x) {
std::cout << "\nYou lose. " << "\n";
++counter2;
}
if (x == y) {
std::cout << "\nDraw. " << "\n";
counter1 += 0;
counter2 += 0;
}
std::cout << " Scoreboard: " << counter1 << " - " << counter2 << "\n";
if (counter1 == 7) {
std::cout << "\n\n Victory! " << "\n";
break;
}
if (counter2 == 7) {
std::cout << "\n\n Loss! " << "\n";
break;
}
}
This is a supposed to be a dice game that calculates the sum of two randomly generated sides of the 6 sided dices. It does it two times and compares the sums to pick the winner with the bigger sum, and it should print out the scoreline every time the the winner is declared. My question is, how can I make the scoreline be updated on the same line as the game continues and not print "scoreboard x - y " every time the round is finished?
Hi from what I' m understanding you want o clear the console like this std::cout << "\033[2J\033[1;1H"; so when you roll the dices again the code comes in the same place but before you do this you need to stop the console make it wait for input and say something like "Press enter to play again" then the console clears and the next game comes in the same place or you can use something like Sleep(milliseconds); before cleaning.
Hope this is what you looking for.
As #enhzflep said this will end up being more than complicated solution for the system dependent code.
However the easy and quick solution is for visually having the same line being updated is to create many empty lines for every for loop iteration.
for (int n = 0; n < 50; n++)
{
std::cout << "\n";
}
As i said earlier this is the best c++ could do when there is no system information available. Using the standard commands.
updated for loop would look like
for (int i = 1; i <= 150; i++) {
int x1{ Human_Roll() };
int x2{ Human_Roll_2() };
int y1{ Computer_Roll() };
int y2{ Coumputer_Roll_2() };
int x;
int y;
x = x1 + x2;
y = y1 + y2;
std::cout << " ----- Game " << i << " -----";
std::cout << "\nYou: " << x1 << " + " << x2 << " = " << x << "\n";
std::cout << "Computer: " << y1 << " + " << y2 << " = " << y << "\n";
if (x > y) {
std::cout << "\nYou win." << "\n";
++counter1;
}
if (y > x) {
std::cout << "\nYou lose. " << "\n";
++counter2;
}
if (x == y) {
std::cout << "\nDraw. " << "\n";
counter1 += 0;
counter2 += 0;
}
std::cout << "---------------------------------------------"
std::cout << "Scoreboard: " << counter1 << " - " << counter2 << "\n";
if (counter1 == 7) {
std::cout << "\n\n Victory! " << "\n";
break;
}
if (counter2 == 7) {
std::cout << "\n\n Loss! " << "\n";
break;
}
for (int n = 0; n < 50; n++)
{
std::cout << "\n";
}
}
There are other ways to do it such as
Sysetm call to clear the terminal
but this method not safe why
The standard way to print end lines
Using the curser library #include <curses.h>
Advantage it is a cross-platform but can not be mixed with standard I/O

Calculation after the for loop is incorrect (C++)

The code I am currently working on is a random walker. The code represents a person taking a step in any random direction (up,down,left,right), then the new location is printed out respectively. In the beginning the user is prompted to enter any amount of steps or how many times the loop should be iterated. The goal of the code is to calculate the squared distance between (0,0)initial and (x,y)final. The distance should be equal to (xx)+(yy) because the initial position that would normally be subtracted is (0,0). The issue or semantic issue I am running into is with the distance calculation. The calculation is not always using the correct x or y value. For example if the final location was (0,-4), somehow x = -1, therefore the distance equals 17 instead of 16. This first example is in image 1. Image 2 is another run for the code. Any help or tips would be greatly appreciated, here is the code:
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include <cmath>
using namespace std;
int main(){
int N;
cout << "Please enter N amount of steps, and for NetBeans users press
'enter' twice." << endl;
cin >> N;
cout << "% RandomWalker " << N << endl;;
int r;
srand( time(0));
int x = 0;
int y = 0;
for(int i = 0; i <= N; i++) {
cout << "(" << x << ", " << y << ")" << endl;
r=rand()%4;
if (r == 0 )
x++;
else if (r == 1 )
x--;
else if (r == 2 )
y++;
else if (r == 3 )
y--;
}
int d = (x*x)+(y*y);
cout << "the distance equals: " << d << endl;
cout << endl;
cout << "x equals before: "<< x << endl;
x = (pow(x,2));
cout << "x equals after squaring: "<< x << endl;
cout << endl;
cout <<"y equals before: " << y << endl;
y = (pow(y,2));
int sum = x + y;
cout <<"y equals after squaring: " << y << endl;
cout << endl;
cout << "x+y after squaring equals: " << sum << endl;
}
for(int i = 0; i <= N; i++)
Since you are starting from 0, the condition should be i < N.
Next issue, is int d = (x*x)+(y*y); The distance formula is
So the initialization should be
int d = sqrt((x * x) + (y * y));
Also what is the point of squaring the x and y values at the end?
You are printing the position BEFORE it is changed based on the value of r. So the last value that's printed out is not the actual final value of x and y, but the one of one step earlier. That's why you're getting unexpected distance.
Sorry for the delayed response, I figured out what I had to do. The object of the assignment was to print out each location and find the squared distance at the end of the loop. Here was the solution for anyone interested.
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include <cmath>
using namespace std;
int main(){
int N;
cout << "Please enter N amount of steps, and for NetBeans users press
'enter' twice." << endl;
cin >> N;
cout << "% RandomWalker " << N << endl;;
int r;
srand( time(0));
int x = 0;
int y = 0;
cout << "(" << x << ", " << y << ")" << endl;
for(int i = 1; i <= N; i++) {
r=rand()%4;
if (r == 0 )
x++;
else if (r == 1 )
x--;
else if (r == 2 )
y++;
else if (r == 3 )
y--;
cout << "(" << x << ", " << y << ")" << endl;
}
x = (pow(x,2));
y = (pow(y,2));
int squaredDistance = x + y;
cout << "The squared distance is " << squaredDistance << endl;
}

Programming a manual square root function?

For my class I'm programming a square root function using inclusion. No, I may not use any other method...
This is my code so far, with the program nearly working. It works for perfect square roots and some other values (like 11 or 5) but it gets into an infinite loop for others (8, 2).
The reason why this happens is that the upper and lower bounds (b and a) do not change. Ideally, the bounds would be current x and previous x, creating new x. What happens is that new x is currently formed by current x and either a or b, being a constant.
I've tried for so long but I have not yet found a way to 'remember' or find the 'previous x', as every time the while loop repeats, only the current x is available for use. Anyone know how such a problem could be solved?
void inclusion ()
{
double v ;
cout << "*** Now solving using Inclusion ***" << endl << "To calculate the square root, enter a positive number: " ;
cin >> v ;
while (v<0)
{
cout << "Square roots of negative numbers cannot be calculated, please enter a positive number: " ;
cin >> v ;
}
cout << endl ;
int n = 0;
while (v >= n*n)
n++ ;
double b = n ;
double a = n-1 ;
int t = 0 ;
double x = (a+b)/2 ;
while ((x * x - v >= 0.1) || (x * x - v <= -0.1))
{
t++ ;
if (x * x < v)
{
cout << "Lower Bound: " << x << '\t' << '\t' ;
cout << "Upper Bound: " << b << '\t' << '\t' ;
x = (b + x)/2 ;
cout << "Approximation " << t << ": " << x << endl ;
}
else
{
cout << "Lower Bound: " << a << '\t' << '\t' ;
cout << "Upper Bound: " << x << '\t' << '\t' ;
x = (a + x)/2 ;
cout << "Approximation " << t << ": " << x << endl ;
}
}
cout << endl << "The answer is " << x << ". Iterated " << t << " times." << endl << endl ;
}
I have not yet found a way to 'remember' or find the 'previous x'
Have a variable previous_x that you previous_x = x at the end of the loop
But that's not your problem. You are changing x, but not a or b, so you get into an infinitely repeating pattern. You should instead adjust whichever bound brings you tighter in.
void inclusion ()
{
double v ;
cout << "*** Now solving using Inclusion ***" << endl << "To calculate the square root, enter a positive number: " ;
cin >> v ;
while (v<0)
{
cout << "Square roots of negative numbers cannot be calculated, please enter a positive number: " ;
cin >> v ;
}
cout << endl ;
int n = 0;
while (v >= n*n)
n++ ;
double b = n ;
double a = n-1 ;
int t = 0 ;
double x;
for (x = (a+b)/2; abs(x * x - v) >= 0.1; x = (a+b)/2, ++t)
{
if (x * x < v)
{
cout << "Lower Bound: " << x << '\t' << '\t' ;
cout << "Upper Bound: " << b << '\t' << '\t' ;
a = (b + x)/2 ;
cout << "Approximation " << t << ": " << x << endl ;
}
else
{
cout << "Lower Bound: " << a << '\t' << '\t' ;
cout << "Upper Bound: " << x << '\t' << '\t' ;
b = (a + x)/2 ;
cout << "Approximation " << t << ": " << x << endl ;
}
}
cout << endl << "The answer is " << x << ". Iterated " << t << " times." << endl << endl ;
}
You need to update the bounds too:
a = x;
x = (b + x)/2;
and
b = x;
x = (a + x)/2;

How to code 'switch' statements concisely to guess a number the user is thinking of

I'm studying Bjarne Stroustrup's "Programming Principles and Practice Using C++". In Chapter 4 you are to create a game where the user thinks of an integer between 1 to 100 and the computer should ask questions to guess the answer. Ideally you should have the answer within 7 questions. My intuition is to ask half of each possible range repeated multiple times, e.g. at first when the range possibilities are 1 to 100 ask the question "Is the number you are thinking of greater or equal to 50?".
Here is a part of my solution showing how I was nesting the switch statements:
char user_answer;
cout << "Is the number >= 50? Answer "yes" or "no" by inputting 'y' or 'n': \a\n";
cin >> user_answer;
switch (user_answer)
{
case 'y':
cout << "Is the number >= 75? Answer "yes" or "no" by inputting 'y' or 'n': \a\n";
cin >> user_answer;
switch (user_answer)
{
case 'y':
cout << "Is the number >= 87? Answer yes or no (you get the idea): \a\n";
cin >> user_answer;
switch (user_answer)
{
While hypothetically creating every eventual yes and no case would result in accurate logic, this code is difficult to maintain and create. Should I be attempting this with a while loop? Functions? I attempted a 'for' loop but I could not implement repetition of the logic explained above.
You're supposed to think of a way where you write as few duplicate code lines as possible.
Yes, you should use a while loop, and appropriate calculations based on the user's answer to further narrow the number range you're asking on each pass of the loop.
You should be thinking about how to make one piece of code that works for every step of the questioning, not a web a if statements.
As an example, you can store an array of possible values [1,100] and have a recurring question that asks whether its larger than the centre of that array.
Depending on the answer you remove the values in the array that are no longer possible and ask again from the new centre of the array. From there you only need a condition check to see if you have an array of size 1 (meaning you know the answer).
i am just starting out on the Stroustrup coursebook as well.
The concepts introduced in chapter 4:
1. iterations
2. Functions
3. vectors
After looking at the advice posted here,
below is what i have. There were alot of trial and error to make sure that i have captured all the numbers.
cout << "Think of a number from 1 to 100, then press y and enter to continue.\n";
char c;
cin >> c;
int min = 1;
int max = 100;
int half(int, int);
vector<int> number;
for (int i = min; i <= max; i++){
number.push_back(i);
}
cout << "Is your number from " << number[min - 1] << " to " << number[(max / 2) - 1] << "? y/n. \n";
// the aim of this loop is to
// 1. bring up the min number to the halfway point between min and max everytime user answer no.
// 2. bring down the max number to the halfway point everytime user answer yes.
while((cin >> c)&&(min!=max)){
if (c == 'n'){
min = half( min, max);
}
else if (c == 'y'){
max = (max + min) / 2;
}
else
{
cout << "I dont understand your input!\n ";
}
cout << "min: " << min << "\t max: " << max << '\n'; // track the limits of the number
if (min == max){
cout << "Your number is " << min << "!\nPress ctrl-z!\n";
}
else if ((min+max)%2)
cout << " Is your number from " << number[min - 1] << " to " << number[half(min, max) - 2] << "? y/n.\n";
// because we added extra 1 in the half function for odd sums, we have to compensate here by deducting 2.
else
cout << " Is your number from " << number[min - 1] << " to " << number[half(min,max)-1] << "? y/n.\n";
}
keep_window_open(); // part of std_lib header, prompts enter character to exit
}
int half (int x, int y){
if ((x + y) % 2){
return ((x + y) / 2) + 1; // because division always round down, so for odd number division we add 1 to be inclusive.
}
else
return (x + y) / 2;
You should go for a function and tell the function what you want it to do.
Here is a quick example that leaves room for improvement.
But you should clearly see that there is a function that gets parameters as an input.
This allows you to use the function multiple times.
I think i know the game you want to program, so the next step is to find the math that generates the new values to call the query function again.
#include <iostream>
#include <string>
int QueryRange(int low, int high, int * result)
{
int error = 0;
using std::string;
using std::cout;
using std::endl;
using std::cin;
string str;
cout << "Is your Number n in the following range? " << low << " <= n <=" << high << " (y/n)" << endl;
cin >> str;
if(0 == str.compare("n"))
{
*result = 0;
}
else if(0 == str.compare("y"))
{
*result = 1;
}
else
{
*result = -1;
error = 1;
}
return error;
}
int main(int argc, char ** argv)
{
using std::cout;
using std::endl;
int low = 1;
int high = 100;
int ret;
while(0 != QueryRange(low, high, &ret))
{
cout << "Unable to read your input" << endl;
}
cout << "your answer was " << ((1 == ret) ? "y" : "n") << endl;
return 0;
}
This is for Chapter 4 Exercise 4 p.128 and is my solution after everyone's input. I wasn't able to use peoples suggestions directly due to the limitations of where I am at in the text book and how the question is worded. I was able to guess the users number in 7 questions or less. Thanks to everyone for the input.
// p128 Exercise 4 write a program to make a numbers guessing game. Use if, else,
// <, and =<, to find the answer of a number 1 to 100 in seven questions or less.
#include "C:\Users\X\Documents\Visual Studio 2013\Projects\std_lib_facilities.h.txt"
int main()
{
char user_answer = ' ';
int min_val = 1;
int max_val = 100;
int quest_number = 0;
int x = 0;
cout << "Welcome to the guessing game!\n-------------------------------------------------------------------------------\n\n";
cout << "Please think of a number from 1 to 100.\n";
cout << "This program will guess what number you chose by asking you yes or no questions. Answer truthfully.\n\n";
cout << "Here is my first of seven questions or less. ";
quest_number = max_val / 2;
for (int i = 1; i < 8; ++i)
{
if (min_val == max_val)
{
cout << "Test: min_val = " << min_val << ", max_val = " << max_val << ", i = " << i << "\n\n";
cout << "The number you are thinking of is " << min_val << "!\n";
keep_window_open("~");
return 0;
}
else if (max_val > 100 || min_val < 1 || min_val > 100 || quest_number > max_val || quest_number < min_val)
{
cout << "The program has had an error. Exiting.\n";
keep_window_open("~");
return 0;
}
else if (max_val - min_val == 1)
{
cout << "Is your number greater than " << min_val << "? Answer yes or no by typing 'y' or 'n': \a";
cin >> user_answer;
if (user_answer == 'y')
{
cout << "I figured it out! Your number is " << max_val << "!\n";
keep_window_open("~");
return 0;
}
else if (user_answer == 'n')
{
cout << "I figured it out! Your number is " << min_val << "!\n";
keep_window_open("~");
return 0;
}
else
{
cout << "That doesn't make sense.";
keep_window_open("~");
return 0;
}
}
cout << "Question " << i << ": Is the number >= " << quest_number << "? Answer yes or no by typing 'y' or 'n': \a";
cin >> user_answer;
if (user_answer == 'y')
{
min_val = quest_number;
cout << "\nTest: the question number = " << quest_number << "\n";
quest_number = min_val + (max_val - min_val) / 2;
cout << "Test: the question number is now = " << quest_number << "\n";
cout << "Test: min_val = " << min_val << ", max_val = " << max_val << ", i = " << i << "\n\n";
}
else if (user_answer == 'n')
{
max_val = quest_number - 1;
cout << "\nTest: the question number = " << quest_number << "\n";
quest_number = min_val + (max_val - min_val) / 2;
cout << "Test: the question number is now = " << quest_number << "\n";
cout << "Test: min_val = " << min_val << ", max_val = " << max_val << ", i = " << i << "\n\n";
}
else
{
cout << "There was an issue with your input.\n";
keep_window_open("~");
return 0;
}
}
}

how to turn if else statement to a switch statement [closed]

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 8 years ago.
Improve this question
i want to know how to turn this if else statement to a switch statement.this is a c++ program to out put the integers in the right order. i can't figure out a way.please help.thank you in advance.
int x, y, z;
cout << "please enter three integers:";
cin >> x >> y >> z;
if (x <= y && y <= z)
cout << x << " " << y << " " << z << endl;
else if (x <= z && z <= y)
cout << x << " " << z << " " << y << endl;
else if (y <= z && z <= x)
cout << y << " " << z << " " << x << endl;
else if (y <= x && x <= z)
cout << y << " " << x << " " << z << endl;
else if (z <= x && x <= y)
cout << z << " " << x << " " << y << endl;
else
cout << z << " " << y << " " << x << endl;
if (x <= y) {
if (z <= x) {
cout << z << " " << x << " " << y << endl;
} else {
if (z <= y) {
cout << x << " " << z << " " << y << endl;
} else {
cout << x << " " << y << " " << z << endl;
}
}
} else {
if (z >= x) {
cout << y << " " << x << " " << z << endl;
} else {
if (y >= z) {
cout << z << " " << y << " " << x << endl;
} else {
cout << y << " " << z << " " << x << endl;
}
}
}
That is not a good way to write a program. What if you need 4 integers?
One way to do it would be to use a list like std::vector and sort it.
vector<int> numbers;
int number = 0;
while (numbers.size() < 3 && cin >> number)
numbers.push_back(number);
sort(cbegin(numbers), cend(numbers)); // sorts ascending by default
for (auto number : numbers)
cout << number << " ";
cout << endl;
You can also use std::multiset which sorts its items automatically as they are inserted.
Instead of this approach, why don't you store the input in an array and try any of the sorting alogrithms to sort your input?
The answer in your particular case is you can't,
Your if statements have particular conditions, which,
wouldn't really work inside a switch.
An example of if/else if/else statements that can be
translated into a switch would be:
if(i == 1) {
// code here
} else if(i == 2) {
// code here
} else if(i == 3) {
// code here
} else {
// code here
}
which would translate to:
switch(i) {
case 1:
//code here
break;
case 2:
//code here
break;
case 3:
//code here
break;
default:
//code here
break;
}
Hope that helps a bit to understand a little more about switch statements.
If the challenge is that you can't sort the numbers, and the limit is 3 integers, then there are better ways to accomplish what you're doing.
#include <iostream>
using namespace std;
int main()
{
int combo[6][3] = {{0,1,2},{0,2,1},{1,0,2},{1,2,0},{2,0,1},{2,1,0}};
int values[3];
cin >> values[0] >> values[1] >> values[2];
for (int i = 0; i < 6; ++i )
{
if ( values[combo[i][0]] <= values[combo[i][1]] &&
values[combo[i][1]] <= values[combo[i][2]] )
{
cout << values[combo[i][0]] << " " << values[combo[i][1]] <<
" " << values[combo[i][2]];
break;
}
}
}
The combo array holds all of the combinations that can occur with 3 slots. Also note that the input is an array. Even if you didn't use the loop, the maximum if() statements you would need is 6.
However you should mention up front that this is a challenge, and what the restrictions are. Otherwise, please look at the other answers concerning storing and sorting these numbers.
You only need three conditional swaps to sort a list of three elements:
int x, y, z;
cout << "please enter three integers:";
cin >> x >> y >> z;
if (y < x) swap(y, x);
if (z < y) swap(z, y);
if (y < x) swap(y, x);
cout << x << " " << y << " " << z << endl;
Note that this approach doesn't scale. For 10 numbers, you would already need 45 conditional swaps.