How does basecase influence which lines of recursive functions are used? - c++

I have the following code in C++ for a recursive function. I don't understand why everything above the basecase is used before basecase is met (stacking?), and then only the lines below the basecase are used as its unstacking.
#include <iostream>
using namespace std;
void printnum(int begin)
{
cout << "upanddown";
cout << begin << endl; //Why is everything this line and above cout'd as it builds the stack and ignored on the unstacking.
if (begin <= 9) { printnum(begin + 1); } // Once the program starts unstacking the functions, why doesn't it console out "upanddown"?
e
cout << begin << endl; //Why is everything below the base case only shown as it unstacks?
}
int main()
{
printnum(1); //First function call, so it starts at one
system("PAUSE");
}
Which results in:
upanddown1
upanddown2
upanddown3
upanddown4
upanddown5
upanddown6
upanddown7
upanddown8
upanddown9
upanddown10
10
9
8
7
6
5
4
3
2
1
Press any key to continue . . .
Why doesn't upanddown execute below the base case ase well?

int main()
{
printnum(1); //First function call, so it starts at one
system("PAUSE");
}
Here is your main function. It has two statements. system("PAUSE"), which is the tail call¸ executed after printnum(1) has returned. To know where to continue it uses the stack for both indicating where to execute next and it's used to give functions arguments. Every call uses the stack so a recursive function is nothing special. The only special thing about it is that it happens to call itself, but the call to itself is independent and the current function is suspended until it has ended just like main. Consider your recursive function:
void printnum(int begin)
{
cout << "upanddown"; // 1
cout << begin << endl; // 2
if (begin <= 9) // 3
{
printnum(begin + 1); // 4
}
cout << begin << endl; // 5
}
So what happens if begin is 10? It will do 1, 2, 3, not 4, then 5.
Output is "upanddowdn10\n10\n".
For begin = 9 it will do 1, 2 which is "upanddown9\n", then the result of printnum(10) is printed since it hits your default case, then "9\n" is printed last. Thus the printed result is "upanddown9\nupanddowdn10\n10\n9\n"
For begin = 8 it will do 1, 2 which is "upanddown8\n", then the result of printnum(9) is printed since it hits your default case, then "8\n" is printed last. Thus the printed result is "upanddown8\nupanddown9\nupanddowdn10\n10\n9\n8\n"
...
For begin = 1 it will do 1, 2 which is "upanddown1\n", then the result of printnum(2) is printed since it hits your default case, then "1\n" is printed last. Thus the printed result is "upanddown1\nupanddown2\nupanddown3\nupanddown4\nupanddown5\nupanddown6\nupanddown7\nupanddown8\nupanddown9\nupanddowdn10\n10\n9\n8\n7\n6\n5\n4\n3\n2\n1\n"
So to answer your question. The "Upanddownx\n" output is done first because it is the first thing to do in your function. If begin is below 10 it will output the whole result of printnum(begin+1). Last it will print "x\n" in the end.

When the flow execution reaches a recursive function call, a function call is made and it starts from the top (That's why you don't see the numbers printed here). When a recursive call reaches the last statement of the function, the execution flow is transferred to the next statement below caller statement (in this case that statement is cout << begin << endl;) That's why you only see the number when backtracking.
Some references about recursion:
Forum
Tutorial

Just remove this line from your code.It is getting those outputs while unstacking.
cout << begin << endl; //Why is everything below the base case only shown as it unstacks?

Related

Cout Not Printing the Return Value from the function

I am trying the Infix to Prefix conversion and evaluation in C++. Someone here guided me and my converstion was resolved easily. But now I am having problems while evaluating it. The problem is that cout is not printing the return value from my function. Following is my code:
int PrefixEvaluation(string s)
{
stack<int> st;
for(int i=s.length()-1; i>=0; i--)
{
if(s[i] >= '0' && s[i] <= '9')
{
st.push(s[i] - '0');
} // if
else
{
int op1 = st.top();
st.pop();
int op2 = st.top();
st.pop();
switch (s[i])
{
case '+':
st.push(op1+op2);
break;
case '-':
st.push(op1-op2);
break;
case '*':
st.push(op1*op2);
break;
case '/':
st.push(op1/op2);
break;
case '^':
st.push(pow(op1,op2));
break;
default:
cout<<"Invalid"<<endl;
break;
} // switch
} // else
} // for loop
cout<<st.top()<<endl;
return st.top();
} // PrefixEvaluation()
int main()
{
cout<<"Prefix Evaluation: "<<PrefixEvaluation("+*^55/9/9*974")<<endl;
} // main
There is no error displayed. The console simply displays a blank screen. Please help. Thank you.
So as #JaMit already explained above, it was a floating point exception. The problem was that I took variables op1 and op2 in int. Therefore, it was only taking the 0 from the previous value and not the complete number i.e 0.xxx. So, I simply changed their data types from int to double and it worked perfectly. Thank you everyone who tried to help.
The console simply displays a blank screen.
That is a problem. Not so much because your program crashed, but because you do not know where it crashed. The traditional remedy for this is to use a debugger, but in this case diagnostic output could be illuminating. Furthermore, for a project like this (a fairly simple console program), I would recommend having diagnostic output from the start so that you can verify your code as you go along.
What would be good diagnostic output? The core of PrefixEvaluation() is the stack st, so add a diagnostic line before every push and pop. This diagnostic should show the pieces you are working with. For example, when pushing a digit:
std::cerr << "Push " << s[i] << '\n'; // Not converted to int
st.push(s[i] - '0');
(I use std::cerr because it is unbuffered, and because it is possible to separate cout and cerr output by redirecting one of them to a file.) Next example, when pushing an operation:
std::cerr << "Push " << op1 << " + " << op2 << '\n';
st.push(op1+op2);
Do this for all the operations, plus the two pops, and you should see why your program crashed:
Prefix Evaluation:
Push 4
Push 7
Push 9
Pop 9
Pop 7
Push 9 * 7
Push 9
Pop 9
Pop 63
Push 9 / 63
Push 9
Pop 9
Pop 0
Push 9 / 0
There you go – you hit a division by zero error. (Note: this is a reason to output the pieces without combining them. If the diagnostic was std::cerr << "Push " << op1/op2 << '\n'; then the diagnostic would unhelpfully crash.) To make your program stable (i.e. work even when the input is bad), you should check for zero before dividing. It's up to you to decide what the program should do in this case. Perhaps you simply want to inform the user and exit.
if ( op2 == 0 ) {
std::cout << "Division by zero!\n";
std::exit(1);
}
st.push(op1/op2);
Don't forget to remove (or comment out) the diagnostics before declaring the project done.
You could get the same result from a debugger. Let the debugger break execution just as the program crashes, then look at the values of your variables at that point. See that op2 is zero. It works, but if you want to find out why op2 is zero, you often have to do another run, breaking multiple times. In contrast, the diagnostic outputs let you quickly trace the source of the zero to 9/63 with just one run.
The speed of tracing the state of your stack is the reason I find diagnostics helpful in this situation. Each test case can be quickly checked not only for the correct final result, but also for the correct computations along the way. The computations stand out, so if you know which should have been performed, you can scan the output to make sure each is present. This lets you check for many potential bugs with not much effort.
Wow, this is some inconsistency in the STL right there.
std::stack<T,Container>::top
reference top();
const_reference top() const;
Returns reference to the top element in the stack. This is the most recently pushed element. This element will be removed on a call to pop(). Effectively calls c.back().
No mention what happens when the stack is empty, no exception thrown when you try it. It just causes plain undefined behavior (exit 139 for me).
Now why is that relevant? Because what you wrote is a postfix evaluator and you feed it with prefix notation. The first character in the string is '+' so you pop 2 elements from the stack that is empty.

What is happening in this function?

I was looking for a method to display the contents of Binary search tree in inorder method. I found this method which seems quite popular but I cannot understand how is this recursion working. How will the code ever reach cout? Also root node is being passed into the function when called by the main function. EDIT: This is considering that "root!=NULL".
void display(struct tree *p)
{
while(p!=NULL)
{
display(p->left);
cout<<p->data;
display(p->right);
}
}
First of all, instead of while(p!=NULL) you should use if (p != null). Otherwise, you get an infinite loop in case the root node is not null.
It first displays the left subtree calling recursively display(p->left). After that it displays the node itself (cout<data) and finally the right subtree calling recursively display(p->right).
Suppose you have the following tree:
4
2 6
1 3 5
A call to display(root), results in the following function calls:
display(4)
display(2)
display(1)
display(null)
cout 1
display(null)
cout 2
display(3)
display(null)
cout 3
display(null)
cout 4
display(6)
display(5)
display(null)
cout 5
display(null)
cout 6
display(null)
When the function is called for node "1", it first displays the left subtree by calling display(p->left).
That function notices p==null returning therefore directly.
So control returns to display(1).
The next statement is cout << 1.
After that, it displays the right subtree by calling display(p->right).
That function notices p==null returning therefore directly.
So again, control returns to display(1).
At this point, display(1) has terminated and control returns to the function that called display(1), being display(2).
It finished its call to display(p->left) (being "1") and therefore executes it next statement, which is cout << 2.
The reason that the code will reach cout is that function display will not recurse all the time.
Once the parameter passed to display become NULL,that is,you have reached the leaf node of that tree, the recursion will start to trace back,the stack will start unwinding.Finally the control will return to the origin call of display.And it begins to execute the cout.
And that's why the judgement while(p!=NULL) is indispensable.

Is there a way to end a program within a void function? [duplicate]

This question already has answers here:
How to end C++ code
(14 answers)
Closed 7 years ago.
I want to know if you can end a program from within a void function. I know that with using void(), you can't just do return 0, so what is there that would allow me to end my program early?
Here is some code to help you understand my situation:
void checkInput(int a) {
if (a is negative) {
cout << "Your number can't be negative" << endl;
// exit program
}
else {
// move on to calculate square root function
}
}
What I am trying to do here is simulate a problem where a function checkInput() will check and see if a number is negative before it goes onto the next function, which actually performs the square root of the number, so I want to make sure it's not negative. If it is negative, I want to exit out of the program. This is just an example program.
You could use C's exit:
void checkInput(int a) {
if (a is negative) {
cout << "Your number can't be negative" << endl;
exit (EXIT_FAILURE);
^^^^^^^^^^^^^^^^^^^^
} else {
// move on to calculate square root function
}
}
For an early return from the function
return;
For an early terminate of the process (abnormal termination)
std::terminate();
For an early exit ("normal" termination)
std::exit(0); // or some other error code
Ultimately, it may be better to define a flow control that allows the program to end after main has completed.
One keyword and a semicolon:
return;
You can use the exit function. It takes a single argument, which is the return value for the program that will be returned to the shell. This function is included from <stdlib.h>
However, the better way would be to add a return value to checkInput since using a exit in the middle of a function is spaghetti code.

While function doesn't work like I want it to

Had a new problem with the while function. As easy as it sounds, I still can't wrap my head around it.
Like my last program, this one closes unexpectedly after the correct and wrong messages.
I want this to loop after entering a number, so that the program won't stop.
Thanks for the help, if any.
#include <iostream>
using namespace std;
int main()
{
int X = 0; //setting the first variable
int num; //setting the second
while (X == 0) //this should happen whenever X is equal to 0
{
cout << "Type a number bigger than 3. "; //output
X++; //This should increase X, so that the next while function can happen
}
while (X == 1) //again, since I increased x by one, (0+1=1 obviously) this should happen
{
cin >> num; //standard input
if (num > 3) //if function: if num is bigger than three, then this should happen
{
cout << "Correct! Try again!" <<endl; //output
X--; //Here I'm decreasing x by one, since it was 1 before, now it becomes 0. This should make the "while (X == 0)" part happen again, so that another number bigger than three can be entered
}
if (num <= 3) //if function: if num is lesser than or equal to 3, this should happen
{
cout << "Wrong! Try again!" <<endl; //output
X--; //This is supposed to work like the "X--;" before, repeating the code from "while (X==0)"
}
}
}
now it becomes 0. This should make the "while (X == 0)" part happen again
Nope. While loops don't magically take effect at any point during execution of the program. You only enter a while loop when you've reached it from code above. Programs are executed top-to-bottom, generally.
You would need a loop around the entire program if you want to keep going round and round. Those whiles you have now should probably be ifs.
Merge the two while loops into one, while(true).
Put each previous while body into an if state with the clause from the old while in it.
while(true) {
if (X==0) {
// the X==0- case
} else if (X==1) {
// the X==1 case
}
}
in order to end your loop, do a break;.
You have to think of C++ programs as a sequence of instructions, like a recipe. while just means a loop: you check the condition. If true, you run the body. After running the body, you check only that condition again, and run the body if true. Whenever the condition is false at the start or end of the body of the while (the {} enclosed code after it), you end the loop and proceed to the next one.
The first loop runs, finishes, then the second loop runs in your code. Once the first loop exits, you do not go back into it just because the condition becomes true.
Understanding flow control is one of the "hard" steps of learning to program, so it is ok if you find this tricky.
There are many improvements you can do your code beyond getting it working -- there is, actually, little need for X at all. But baby steps! Once you get it working, you can ponder "how could I remove the variable X?".
Before making such fundamental changes to your program, you should get it working, and save a copy of it so you can "go back" to the last working version.
You want to wrap all that code in it's own while loop:
while (true /* or something */)
{
while (X == 0) //this should happen whenever X is equal to 0
{
// ...
}
At least put your second while loop inside the first one to get it working as intended. Otherwise your program has no reason to go back again.
Nevertheless it's not a good design.

C++ Function will not execute more than once

I've tried looking around but I can't find anything about this anywhere.
I'm writing a custom array class with a "push" function to add a value to the array.
It seems to work perfectly fine but won't execute more than once.
Take the main method below for example:
int main()
{
Array<int> test(4,5);
test.push(4);
test.writeOrdered("Output.txt");
return 0;
}
This will put the int value 4 into the array at the first available position and execute the writeOrdered function.
The following main method, on the other hand:
int main()
{
Array<int> test(4,5);
test.push(4);
test.push(5);
test.writeOrdered("Output.txt");
return 0;
}
This will put the number 4 into the array at the first available point as above and then stop. It won't execute any further lines of code.
Here's the push function for reference:
void push(Datatype p_item)
{
bool inserted = false;
int i = 0;
while (inserted == false)
{
if (m_array[i] < 0)
{
m_array[i] = p_item;
i++;
inserted = true;
cout << p_item << " saved to array" << endl;
system("pause");
}
}
}
You have an infinite loop. After the first insert m_array[0] >= 0 and i never grows. You would have found it out, had you debugged the code somehow.
Basically I don't understand your push function but the way it is, after you insert a non-negative value into the first position any further call to your push function results in a tight loop.
I imagine that you want the i++ outside the if statement.
Without seeing the full implementation of the Array class I would guess that the array m_array contains negative numbers by default. This will allow the first call to the push method to succeed. The next call to the method contains a value of 4 at index 0 and will be stuck in an infinite loop because inserted will never be set to true nor will the value of i be incremented.