So, have an assignment where I need to solve the N-Queens* problem using the stack.
*N-Queens problem: you have a chessboard with N rows/columns/queens. You must place each queen so that it cannot attack any of the others on the board.
I created a Queen class just to store the row and column positions for each valid queen placed, and that is working fine. As far as I can tell, all of my sorting and checking logic is also fine. However, either in main or my solve function, I'm getting a Segmentation Fault, but only when I debug. When ran normally, it just exits. My debugger unfortunately doesn't let me go line by line, but I've manually done so and still can't figure this out.
void solve(int k, int N)
{
stack<Queen> queenStack;
if(k == N)
{
while(!queenStack.empty())
{
cout << queenStack.top().rowPos << ", " << queenStack.top().colPos << endl;
queenStack.pop();
}//end while
}//endif
else
{
for (int i = 0;i < N; i++)
{
if (isSafe(k,i))
{
Queen queen(k,i);
queenStack.push(queen);
solve(k++,N);
}//end if
else
{
if(queenStack.empty())
{
break;
}//end if
else
{
queenStack.pop();
k--;
}//end else
}//end else
}//end for
}//end else
}//end void
then my main:
int main()
{
int N = 0;
cout << "Please pick an integer 3 or greater and less than whatever you think won't crash your computer." << endl;
cin >> N;
while (N < 3)
{
cout << "Please pick an integer 3 or greater and less than whatever you think won't crash your computer." <<
endl;
cin >> N;
}//end while
solve(0,N);
return 0;
}//end main
my ifSafe is a bool function that just does checks based on row, which I pass in as an int, and then return the true/false for the loop.
First of all, there's an obvious issue in your code that will immediately lead to a stack overrun. The way you recursively call your solve function:
solve(k++,N);
Will first call solve, and then increment k. So solve(0, N) calls to solve(0, N), which in turn calls to solve(0, N) leading to stack overrun. There's no side effects or any external variables that would affect solve and make it behave differently with the same arguments.
I don't fully understand your solution, so I can't tell you how to fix it, but most likely your intent was for queenStack to be visible across the calls, in which case it would make sense to make it global, or to pass it into the solve by reference.
Now to why it finishes just fine when you run it outside of the debugger. My guess would be that you use some kind of non-windows system (mac or linux) and run it from the terminal. This way the program still crashes, but does not show it in any obvious way. The way to see if it finished successfully is to print $? after executing a program:
a#a-dev:~$ ./crash_me
a#a-dev:~$ echo $?
1
If the program executed normally, the return code should be zero.
Related
Hi I am using Codeblocks and a problem occurs when I start this program:
int number_STABLE= 2;
int number_VARIABLE;
int numberof_STEPS = 0;
void Check() {
number_VARIABLE=number_STABLE;
while (number_VARIABLE!=1) {
if (number_VARIABLE%2!=0) {
number_VARIABLE=(number_VARIABLE*3)+1;
} else {
number_VARIABLE=number_VARIABLE/2;
}
numberof_STEPS++;
}
}
int main()
{
cout<<" - STARTED - "<<endl;
cout<<endl;
while (numberof_STEPS!=555) {
numberof_STEPS=0;
cout<<"Stable: "<<number_STABLE<<endl;
cout<<endl;
Check();
number_STABLE++;
number_VARIABLE=0;
cout<<"Steps: "<<numberof_STEPS<<endl;
cout<<endl;
}
cout<<"Number of steps: "<<numberof_STEPS<<endl;
cout<<endl;
cout<<"Last number: "<<number_STABLE-1;
return 0;
}
It runs for approximately two minutes then it stops. When closing the console app window this is the error message displayed in the Build log:
Process terminated with status -1073741510 (1 minute(s), 54 second(s))
Could someone explain why this happens and/or how can I prevent it?
First of all, these two lines are nonsense:
while (numberof_STEPS!=555) {
numberof_STEPS=0;
This loop will never exit.
Second: Do not use global variables as loop variables. Automatic variables are much faster because they will be put into a register. Incrementing the variable outside the function containing the loop makes it all worse because the program becomes totally incomprehensible.
Third: Your technical problem presumably is an integer overflow. The Collatz sequence rapidly reaches the 2^31 limit. Try this one:
int i;
i = 2147483647;
cout << i << endl;
i++;
cout << i << endl;
I am trying to write a code to print values using function and the program doesn't print anything and I don't know why. I know void function don't return any value so I put cout inside the function and I call is correctly
#include <iostream>
using namespace std;
void Print(int n){
for (int i = 0; i <= n; i++){
if (n%i == 0){
cout << i << ' ';
}
}
cout << endl;
}
int main(){
int x;
cin >> x;
Print(x);
return 0;
}
Start your loop from 1 in Print function. You can not mod a number with 0. Division by zero is not allowed.
When you run your program, it wont print anything. You have to enter a number first, then press Enter/Return, and then it should print something.
Assuming you do this and it still does not print, that will be because your Print has a loop that starts from i = 0, and you then do n % i. Doing the modulo % operation with a right-hand-side operand of 0 is not going to work. Start the loop from i = 1 or something else >0.
Lastly, your program will terminate in main at the return 0; right after the first Print. This means that most of your main won't actually be executed. This is probably intentional, but keep that in mind.
Fix these issues and make sure you enter a number into your program when it runs that is valid, like 12, and it should print something.
so that's my first time learning a language , and I was really excited to play with classes, i do have one major problem which i cant seem to understand ;
im building a bank menu . its a class ofcourse, and i have a different class of clients which is basicly an array in my bank.
so my menu function inside the bank looks like that :
void menu (){
manager();
int n,m;
cout << "welcome to our bank managment system. \n";
cout << "please choose one of the following options : \n";
cout << "1-add a new client\n";
cout << "2-remove a leaving client\n";
cout << "3-bank statistics\n";
cout << "4-if you are a costumer\n";
cout << "5-exit\n";
cin >> n ;
if()
if()
if()
if()
if()
note that my return function is been summoned a lot inside
i have a return function to go back to the menu :
void returnfunction (){
int back = 0;
cout << "\n0-back to menu \n press a diffrent number back to exit :)\n";
cin >> back ;
if (back==0){
return menu();
}
if (back!=0){
cout << "thank you for using our program ! ";
return ;
}
it is working perfect until i play with it to much , and then hit 5 to exit (that's my option for n==5)
i must emphasize that when im hitting 5 only after few simple actions its working fine...
how can i fix that return function ?
ofcourse my main looks like that :
int main()
{
srand (time(NULL));
Bank b ;
b.menu();
}
appricate all of your wisom , thanks a lot
Your function:
void returnfunction ()
is declared to return nothing (void) but you:
return menu();
do return something, that's very unclear (even though menu() returns void too)
If you want to call menu() and then return write:
menu();
return;
There are a couple problems with this code, and honestly it wouldn't compile in other imperative OO languages. But this is c++ where the rules don't matter. Aside: If you don't have a strong reason to be using C++, learn Rust first. I promise you'll thank me later.
Paul has the right of it. The compiler should error out at that statement:
return menu();
However the equivalent is perfectly legal:
menu();
return;
But this still will cause problems in theory (but maybe not in practice) because your function is almost, but not, a candidate for tail recursion optimisation. More here Which, if any, C++ compilers do tail-recursion optimization?
This becomes a problem when users return to the menu many times, it depletes your programs memory, eventually leading to a stack overflow fault. The common pattern you'll find in most every GUI / Graphics library is that of a main-loop. Something like:
int main() {
bool exit = false
while(!exit) {
int action = menu()
switch(action) {
case EXIT_SELECTION: exit = true; break;
case SHOW_STATISTICS: printStats(); break;
}
}
}
Each time you call a function, your program has to use more memory to keep track of everything related to that function call. Ordinarily this memory is released once a function ends, but because your menu function calls another function that calls your menu function that calls another function... and on and on, you will eventually run out of memory from all of the function calls since these functions cannot terminate until the functions they call terminates -- and thus your program will crash. The solution is to use a while loop and check the user's input for an exit code as a previous responder mentioned. It can look something like:
`void menu() {
char choice= '\0';
while(choice!= 3) {
std::cout << "Welcome to the menu!";
std::cout << "\t Option 1 \n";
std::cout << "\t Option 2 \n";
std::cout << "\t Option 3 \n";
std::cout << "Your option: ";
std::cin >> choice;
if(choice == 1) { /*do something*/ }
else if(choice == 2) { /*do something else*/ }
else if(choice == 3) { /*print a message and exit*/ }
else { /*bad choice -- try again*/ }
} //end while-loop
} //end menu()`
Also, notice that your functions' return types are void, which, by definition, cannot have any sort of return. C++ will allow you to say return; inside of a void function, but it is merely a way to escape the function right then and there and is not really intended to do anything more than that. Using return in any other way when working with void functions is confusing and runs a risk of causing big issues.
This is the function in question. The variable in question is count1. Prior to return count1; the function appears to reset count1 to either 1 or 2. The result of the final cout line is n lines where n=number of tries including the correct answer. Each line outputs a number that is 1 higher than the line below until count1 = either 1 or 2. I haven't been able to establish a pattern as to which it will finally output.
The questions themselves are simply placeholders.
What on Earth is going on?
Note: I am a very new programmer, and I am aware that there are likely more efficient ways to do what I am doing that I have not learned. I'm open to suggestions, but my understanding of those suggestions will likely be hampered by my unfamiliarity with C++
int q1(int count1) //q1() is always fed a value of 1.
{
using namespace std;
if (count1 <= 3) //User gets 3 tries to answer for full credit.
{ //count1 is returned in order to determine user score.
cout << "What is 2+2 \n"; //problem appears to occur between here and the end of this if statement.
double a1;
cin >> a1;
if (a1 == 4)
{
cout << "Yup. You know what 2+2 is. \n\n";
}
else
{
wrong(); //wrong() is a single line void function using std::cout and nothing else.
q1(++count1);
}
}
else
{
cout << "You have used all three tries. Next question. \n\n";
++count1; //count1 is incremented for an if statement in int main()
}
cout << count1 << "\n"; //This line is strictly for debugging
return count1;
}
Output of the final cout line looks along the lines of this:
5
4
3
2
Without \n
5432
EDIT:
There was an answer below that is deleted for some reason that appeared to resolve my problem.
The answer stated I should replace q1(++count1) with count1 = q1(++count1);
In my mind this shouldn't work, but in practice it seems to work. Why?
When using recursion, the first time your function runs count1 is 1 (as you said). If the user answers right, then your function will return 1, because the value of count1 never changes.
If the user answers wrong, then count1 increases by 1 and gives it's value to a new function (of the same type). Keep in mind that you pass the value of count1, that means the new function (the second q1()) will get the number 2 but will have a new variable count1. They may have the same name, but they are different variables.
There are two ways to solve your problem:
Either by using pointers, this way you pass the address of count1, and each function changes the same variable. (This is the hardest way and not the most efficient) or
Instead of making recursive calls, you can make a while like so:
int q1(int count1)
{
using namespace std;
while (count1 <= 3) //Run as long as user has chances
{
cout << "What is 2+2 \n";
double a1;
cin >> a1;
if (a1 == 4)
{
cout << "Yup. You know what 2+2 is. \n\n";
//Using `break` you stop the running `while` so the next
//step is for the function to return
break;
}
else
{
wrong();
//By incrementing `count1` the next time the `while` runs
//if user ran out of tries it will not enter the loop, so
//it will return `count1` which would most likely be 4
count1++;
}
}
//Here the function is about to return, so you check if user won or lost
if (count1 == 4)
cout << "You have used all three tries. Next question. \n\n";
//Debug
cout << count1 << "\n";
//Return
return count1;
}
When the condition is true or false, how can I make it return back and ask the question again, making the user re-enter the value?
Here is what I want to implement:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int n;
cout<<"Enter numbers. Press 5 to stop: ";
cin>>n;
bool tr=true;
while(tr)
{
if(n!=5)
cout<<"You entered "<<n; //How to make it return again, since its false? I keep getting infinite loops :( ;
else
tr=false;
}
return 0;
}
You need to prompt the user in the while loop, so that it occurs in each iteration:
int n;
bool tr = true;
while(tr)
{
cout << "Enter numbers. Press 5 to stop: ";
cin >> n;
if(n!=5) {
cout << "You entered " << n;
} else {
tr = false;
}
}
Just put all your code (except 'n' and 'tr' definition) in while loop as follow:
int main()
{
int n;
bool tr=true;
while(tr)
{
cout<<"Enter numbers. Press 5 to stop: ";
cin>>n;
if(n!=5)
cout<<"You entered "<<n;
else
tr=false;
}
return 0;
}
The other answers all work, and there is something to be learned about improving program flow from them, but I believe the trick you're asking for is the continue keyword, which skips the remainder of this iteration of the loop.
bool tr = true;
int n;
while (tr)
{
cout << "Enter numbers...";
cin >> n;
if (n != 5)
continue;
else
tr = false;
}
EDIT Part 1: On the continue keyword.
You want to make your code as readable as possible. In this example, its use is unnecessary (as the other posters have shown); but it is the answer to the question "How do I skip the rest of processing in this iteration of my loop and continue to the next iteration?". Usually, such flow-breaking directives actually make code harder to read; but sometimes the opposite is true. Anything (or, at least, almost anything) that can be accomplished with continue or break, can be accomplished without them, so if you're going to use them, you want to have a definite reason for doing so. Usually, when I use continue, it's because I'm looping through a collection of inputs and I want to skip processing the loop whenever the input isn't in the format I'm expecting. Something like this (pseudo-code)...
foreach (Input i in ReceivedInputs)
{
if (i.isBad())
{
cout << "Bad input";
continue;
}
// Do massive block of calculating here.
}
is easier to read than this...
foreach (Input i in ReceivedInputs)
{
if (i.isBad())
cout << "Bad input";
else
{
// Do massive block of calculating here.
}
}
because the second version makes it harder to track what scope you're in, if you're looking toward the end of the massive block of calculating. In this case, I gain code readability by continue, so I use it. But simple code probably shouldn't use it. The break keyword is similar, though it's a lot easier to come up with examples where break is beneficial.
EDIT Part 2: On multiple iterations
This is just an issue of setting up the loop; there are no magic keywords here. The shortest way I can come up with, is probably something like this:
int n = 0;
int numberToTake = 10;
for ( int numbersTaken = 0; numbersTaken < numberToTake; ++numbersTaken)
{
cout << "Enter numbers...";
int n = 0;
for (cin >> n; n != 5; cin >> n)
cout << "Try again.";
// Do whatever processing on n you want to do here.
}
Though I should point out that, doing it this way, the only value you will ever get from the user will be 5, and if he inputs anything that doesn't fit in an integer, you will get unexpected behavior.
EDIT 3: After reading the comment more thoroughly, I think you're just looking for is the more traditional use of the for loop.
No need for the exra bool variable.
The idiom can be: Infinitely loop until the user enters 5:
for(;;) { // Loops infinitely
cout << "Enter numbers. Press 5 to stop: ";
cin >> n;
if(n == 5)
break; // Exits the loop
cout << "You entered " << n; // Before the if if you want to print 5 as well
}