Recursive Function Always Returns False - c++

My recursive program does not return true when it reaches the specified target, even when it looks like it should. It simply returns false, then terminates, and I can't figure out why.
I've tried to rearrange the order of the If/Else statements in every possible way, I've attempted to debug it using cout, and it looks like it should return true, but it doesn't.
#include <iostream>
using namespace std;
bool isNumberInArray(const int anArray[], int first, int last, int targetNum) {
if (first > last) { //if last number is less than the first number to be searched
return false; //Returns false if the size of the array to be searched is less than the first element of the array
}
if (anArray[last] == targetNum) { //if number at "last" position is equal to the target
return true; //Returns true if the target is found at the last position
}
else { //run again, with last = last - 1
cout << "searching for " << targetNum << "; ran else; position " << last << " value " << anArray[last] << "\n";
//previous line used for testing purposes
isNumberInArray(anArray, first, (last - 1), targetNum);
}
}
int main() {
int numberArray[10] = {1, 2, 3, 11, 5, 6, 7, 8, 9, 10};
if (isNumberInArray(numberArray, 0, 9, 11t))
cout << "True\n";
else
cout << "False\n";
return 0;
}
The program should realistically return "true" when the value of last reaches the position that targetNum is located at, but instead it always returns false, even if it is true, and I can't figure out why. The cout statements that I placed within the function even stop when the program reaches the targetNum, but it still returns false:
searching for 11; ran else; position 9 value 10
searching for 11; ran else; position 8 value 9
searching for 11; ran else; position 7 value 8
searching for 11; ran else; position 6 value 7
searching for 11; ran else; position 5 value 6
searching for 11; ran else; position 4 value 5
False
11 is at position 3.

You need to return the result of your recursive call inside your else clause.
else { //run again, with last = last - 1
cout << "searching for " << targetNum << "; ran else; position " << last << " value " << anArray[last] << "\n";
//previous line used for testing purposes
return isNumberInArray(anArray, first, (last - 1), targetNum);
}
It will return true if the the first item you consult is what you're looking for, however, it will never check further calls of isNumberInArray(), as you never check that value. When the program eventually works it way back up to the first call, it'll enter if (first > last) and return false, when it should in fact be returning the value from isNumberInArray.

Related

Can't figure out this stack output c++

So I have a stack example I created following a tutorial using the stack library
stack<string> custs;
custs.push("george");
custs.push("louie");
custs.push("florence");
// cout << "size" << custs.size() << endl;
if (!custs.empty()) {
for (int i = 0; i <= custs.size(); i++) {
cout << custs.top() << endl;
custs.pop();
}
}
I ran this and got the output:
florence
louie
My question is why isn't it outputting George as well? The program outputs the top data then pops it. This means it should output Gorge then pop it after. Why doesn't this happen? initially the code was i < cust.size so I thought because i is not less than 1 it would not ouput. So I switched it to <= and it still doesn't output George. How come?
It is because you are both increasing i and reducing the size of the stack in the loop.
You can rewrite your loop like this:
while (!custs.empty()) {
cout << custs.top() << endl;
custs.pop()
}
Here is a step by step explanation of what is happening so you can understand it better:
First, i starts as 0, and custs.size() returns 3. Since 0 <= 3 is true, the body of the loop executes, printing "florence" and removing it from the stack.
On the second iteration, i equals 1, and custs.size() returns 2, because you had 3 items but you removed one. Since 1 <= 2 is true, the body of the loop executes again, printing "louie" and removing it from the stack.
Then, i equals 2, and custs.size() returns 1, because you already removed 2 elements. Since 2 <= 1 is false, the body of the loop doesn't execute, and the loop ends.
As you can see, the problem is that your loop's condition changes on each iteration. There are a couple of ways to fix this:
int s = custs.size();
for (int i = 0; i < s; i++) {
cout << custs.top() << endl;
custs.pop();
}
By doing that, you store the original size of the stack, so you can iterate without problems.
Another solution would be to check if the stack is empty on each iteration with a while loop:
while (!custs.empty()) {
cout << custs.top() << endl;
custs.pop();
}
By doing that, you check if there are any elements left to print each time.
Hope this helps!
When you use for loop like this
for (int i = 0; i <= custs.size(); i++) {
cout << custs.top() << endl;
custs.pop();
}
it loops directly till the size of stack which decreases in each iteration.
which in my opinion is the main reason your code is not working. I rewrite this as
int z = custs.size() ;
for(int i=0;i<=z;i++)
{
cout<<custs.top()<<endl;
custs.pop();
}
and it worked perfectly fine. In my opinion, the best approach is to use while loop like this
while(!custs.empty())
{
cout<<custs.top()<<endl;
custs.pop();
}

Regarding Recursive Functions in C++ (Beginner Level)

So I've just started C++ programming, and am a little stuck on one particular program that was used to demonstrate how recursive functions work. I do know the premise of recursive functions, that being a function which calls itself until an exit condition has been met. I understood the concept using the program for factorials,
int factorial(int n)
{
if (n==1)
{
return 1;
}
else
{
return n*factorial(n-1);
}
}
the if statement being the exit condition in the above code.
However, the code that tripped me up was from this link:
http://www.cprogramming.com/tutorial/lesson16.html
specifically this code:
#include <iostream>
using namespace std;
void printnum ( int begin )
{
cout<< begin<<endl;
if ( begin < 9 ) // The base case is when begin is greater than 9
{ // for it will not recurse after the if-statement
printnum ( begin + 1 );
}
cout<< begin<<endl; // Outputs the second begin, after the program has
// gone through and output
}
int main()
{
printnum(1);
return 0;
}
OP:
1
2
3
4
5
6
7
8
9
9
8
7
6
5
4
3
2
1
In the immediately above code, I understand the output till the first 9. But after that, why does the cout statement following the if loop cause the begin variable to start counting backwards till it reaches the value it originally was when printvalue was first called? I suppose I don't really understand the exit condition here.
Not sure what I'm missing, and any help would be greatly appreciated.
Thanks.
Each begin is unique and belongs to the "current" active function – its value never changes.
Recursive functions work exactly like other functions; it doesn't matter to one what the parameter of another is named.
If you had these:
void f(int x);
void g(int x)
{
cout << x << endl;
f(x+1);
cout << x << endl;
}
you would be very surprised (I hope) if g printed two different numbers.
Your recursion works exactly like this (much smaller) example that uses unique functions instead of recursion with a parameter:
void printnum_3()
{
cout << 3 << endl;
cout << 3 << endl;
}
void printnum_2()
{
cout << 2 << endl;
printnum_3();
cout << 2 << endl;
}
void printnum_1()
{
cout << 1 << endl;
printnum_2();
cout << 1 << endl;
}
int main()
{
printnum_1();
}
So, lets see what happens when printnum(1) is called.
begin equals 1, it is printed with cout and then printnum(2) is called.
But what happens when the program leaves printnum(2) function? It continues to execute printnum(1) from the place, where printnum(2) was called. So, the next line to execute is cout << begin. begin still equals 1, because we are executing printnum(1) function. This is why 1 is printed once again at the end. The situation is totally the same with other function calls.
For example, when printnum(9) is called, it prints 9, then the if check fails (begin is not less, than 9) and then 9 is printed once again.
why does the cout statement following the if loop cause the begin variable to start counting backwards till it reaches the value it originally was when printvalue was first called?
To start with, there is no loop. There is call stack which you need to understand. Recursive call stops when (begin < 9) becomes false i.e. when begin = 9. You are seeing the call stack unwinding.
First cout in the function is printing sequence [1..9], and second cout is printing the decreasing sequence [9..1].
Your code execution is like this:
cout<< 1 <<endl; //enter1
cout<< 2 <<endl; //enter2
cout<< 3 <<endl; //enter3
...
cout<< 8 <<endl; //enter8
cout<< 9 <<endl; //enter9
cout<< 9 <<endl; //exit9
cout<< 8 <<endl; //exit8
...
cout<< 3 <<endl; //exit3
cout<< 2 <<endl; //exit2
cout<< 1 <<endl; //exit1

c++ Recursion array explanation

Hello i am learning recursion and currently i have couple of trick problems to dissect - here is one of recursive functions
int rec(int niz[], int start, int end){
if (start == end)
{
return niz[start]; // vraca zadnji
}
int temp = rec(niz, start+1, end);
// control output
cout << "\n-----\n";
cout << "start " << start << endl;
cout << "niz[start] " << niz[start] << endl;
cout << "end " << end << endl;
cout << "temp " << temp << endl;
cout << "\n-----------------------------------------\n";
//contrl output end
return ((niz[start] < temp) ? niz[start] : temp);
}
i included a cout block to control what is gong on in calls. here is main part
int niz[] = {1,2,3,4,5,6,7};
cout << rec(niz, 0, 3);
and here is my output:
-----
start 2
niz[start] 3
end 3
temp 4
------------------
-----
start 1
niz[start] 2
end 3
temp 3
------------------
-----
start 0
niz[start] 1
end 3
temp 2
------------------
1
can anyone explain me how is temp value being calculated and returned and how i am getting 1 as the return of this function?
Thank You in advance!
Recursive function is the function that calls itself.
int temp = rec(niz, start+1, end);
Here you call the "rec" function inside the one, but with the changed parameter (start + 1). You call these function inside each other until the "start" equals "end" (then it returns)
if (start == end)
{
return niz[start]; // vraca zadnji
}
After the deepest one returns the second deepest one continues its flow, printing some information.
cout << "\n-----\n";
cout << "start " << start << endl;
cout << "niz[start] " << niz[start] << endl;
cout << "end " << end << endl;
cout << "temp " << temp << endl;
cout << "\n-----------------------------------------\n";
Then it it returns the lowest value between niz[start] and temp (local values).
return ((niz[start] < temp) ? niz[start] : temp);
Then the third deepest one continues its flow and so on. Until it gets to the first function.
In your main part you set the end to 3, so it performs the operation on the first 3 elements (it gets to the fourth element, but doesn't do anything beside returning its value). You get 1 by comparing the niz[0], that you passed as start, and temp that is returned by recursive function (which happens to be the same). It equals, so the return value is niz[0] that is 1;
When using recursive functions, you should have some kind of "exit point" that prevents the recursion to become infinite, i.e.
if (start == end)
{
return niz[start];
}
In general, recursive functions look like this:
f()
{
//return condition
//some work
f();
//some work
//return
}
And you can look at them as this
f()
{
//some code
f()
{
//some code
f()
{
//some code
f()
{
...
//eventually the return condition is met
}
//some code
//return
}
//some code
//return
}
//some code
//return
}
Keep in mint that unhandled recursion may lead to possible memory leaks, because each function call comes with additional data.
f()
{
f();
}
This will lead to stack overflow due to system data that has been created;
You may want to watch "Inception" to understand it better :)
rec(niz, 0, 3) (D)
|
---->rec(niz, 1, 3) (C)
|
----> rec(niz, 2, 3) (B)
|
----> rec(niz, 3, 3) (A)
You call (D) which calls (C) to calculate temp and so on up to (A). In (A) start==end and it returns niz[3]=4.
In (B):
temp = 4 (result of (A))
start = 2
As 4 is bigger than niz[start]=3 (B) returns 3
In (C):
temp = 3 (result of (B))
start = 1
As 3 is bigger than niz[start]=2 (B) returns 2
In (D):
temp = 2 (result of (C))
start = 0
As 2 is bigger than niz[start]=1 (B) returns 1
Your recursive line is before your print statement block. By nature of recursion, it makes the function call on that recursive line and stops the caller function's execution until the callee is done. Therefore you call for the next element to be processed before you print the current element.
In your example the following is happening:
Layer 1:
Is start equal to end? No.
What is the result of the next element? Don't know yet, recurse.
Layer 2:
Is start equal to end? No.
What is the result of the next element? Don't know yet, recurse.
Layer 3:
Is start equal to end? No.
What is the result of the next element? Don't know yet, recurse.
Layer 4:
Is start equal to end? Yes!
Return the current element, 4.
End layer 4.
Layer 3:
Now know next element, start printing for the 3rd element.
Return 3.
End layer 3.
Layer 2:
Now know the next element, start printing for the 2nd element.
Return 2.
End layer 2.
Layer 1:
Now know the next element, start printing for the 1st element.
Return 1.
End layer 1.
End program.
As you can see, the array elements are printed backwards because the print statements are after the recursive call. I'd you want them to be printed in order, print them before the recursive call, or create a buffer and append each print section to the front of the buffer.

c++ why this error "basic_string::substr" and breaking up the loop

i am trying to get the last letters of a word, to compare if these letters row are in a vector.
So i want to check first the last 2, then the last 3 and the last 4 letters. As soon as it finds one, it should break up, and return false. Else it should check everything left, and return in case of nothing founded, true.
This my function:
bool isIt(wstring word, vector <wstring> vec) {
int ct = 2;
while (ct < 5) {
word = word.substr(word.length() - ct, word.length()-1);
//wcout << word << endl;
if (find(vec.begin(), vec.end(), word) != vec.end()) {
//wcout << "false" << endl;
ct = 5; return false;
} else {ct++; wcout << ct << endl; continue; }
} return true;}
the function get called thru this:
if( word >3){ isIt(word, vec); }
when the first check does fail, i receive this error msg:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr
i don't understand, why it does not continue, once it is in the else part.
I hope my description was good enough.
BR
The bug is here, where you modify word.
word = word.substr(word.length() - ct, word.length()-1);
If word is "ABCD" entering this function then the first time through the loop this evaluates to:
word = std::string("ABCD").substr( 2, 3 );
And the second time through your loop it evaluates to:
word = std::string("CD").substr( size_t(-1), 1 );

Why does this code sort of work?

I started writing this code a few days ago. I saw a question on here that got me wondering about variable argument lists, so I wrote (never really finished, but it has the functionality I was curious about) this piece of code:
void VendingMachine::setStamps(int largest, ...)
{
cout << "Setting stamps to: \n";
vector<int> tmp;
vector<int>::iterator iter;
int next = largest;
va_list lst;
va_start(lst, largest);
while(next != NULL)
{
cout << next << "\n";
tmp.push_back(next);
next = va_arg(lst,int);
}
va_end(lst);
stamps = new int[tmp.size()-1];
int i = 0;
for(iter = tmp.begin(); iter != tmp.end();)
{
stamps[i] = *iter;
iter++;
i++;
}
cout << "The array is now: ";
showStamps();
}
void VendingMachine::showStamps()
{
cout << sizeof(stamps) << " " << sizeof(*stamps);
for(int i = 0; i < NUM_OF(stamps); i++)
cout << stamps[i] << ", ";
cout << "\n";
}
Now, what I'd expect is for setStamps to never finish. Or at least take a very long time, and a variable amount of time, since no part of the list is guaranteed to be NULL unless it was supplied. This isn't the case. I call setStamps with v.setStamps(90,30,24,15,12,10,5,3,2,1); and it prints this out:
Setting stamps to:
90
30
24
15
12
10
5
3
2
1
-217832717
The array is now: 4 490,
Ignoring the last line, since that was me messing around trying to figure out how to determine the length of an array, this doesn't make sense. It stopped after the first value that was outside of the passed arguments. It should have kept going until there was a NULL value, and there shouldn't be one of those in the same place each time. But the outcome is always the same: 90, 30, 24, 15, 12, 10, 5, 3, 2, 1, [number that changes each time]. There's never any additional values. It's a mystery.
and there shouldn't be one of those in the same place each time
Who says there won't be one in the same place every time? The behavior is undefined, and so having a NULL value in the same place every time is entirely possible.