recursive divison of number - c++

I have following code to divide one number recursively by another number:
#include <iostream>
using namespace std;
int divide(int number,int dividend){
int answer=0;
if (number>dividend || number==dividend ){
answer+=1;
return divide(number-dividend,dividend);
}
return answer;
}
int main(){
cout<<divide(20,5)<<endl;
return 0;
}
but unfortunately I get zero as answer. Do you see what is wrong?

Answer is a local variable. When you run this code, the first call to divide creates an instance of the answer variable, sets it to 0, and then increments it to 1. Then, when you recursively call divide again, it creates a brand new instance of the answer variable, sets that instance to 0, and then increments that instance to 1.
In your final call to divide, it creates a brand new instance of the answer variable, sets that instance to 0, but since now number<=dividend it doesn't increment it, and it returns that instance of answer which is 0.

In the if branch you are incrementing answer but returning something unrelated (the result of the recursive call). I am sure, this is not what you want. Go from there.

You are recursively running the following code:
if (number>dividend || number==dividend ){
answer+=1;
return divide(number-dividend,dividend);
}
But once the recursive calling ends (which is number < dividend), you will ignore the if statement and return 0;

You do int answer=0; in the start of function call, so when the if statement is wrong, it returns 0 so you should define it as input parameter (by reference call) or make it global (not recommended) and do not set it to zero, just set it before your recursive function call.

Related

how does a function with 2 recursive call works?

I have been trying really hard to understand this question.
Question is:- In a mathematics class, Teacher ask Alice to find the number of all n digit distinct integers which is formed by the two distinct digits a and b but there is a rule to form n digit integer.
Rule: She has to form n digit integer by using two digits a and b without consecutive b.
Input Format:-
The first line contains T, the number of test cases. Further T lines contains the value n which is the number of digit in the integer.
Code:-
#include<bits/stdc++.h>
using namespace std;
void classAssignment(int n,string ans, int &count){
if(ans.length()==n){
cout<<ans<<endl;
count++;
return;}
classAssignment(n,ans+"a",count);
if(ans.length()==0 || ans.at(ans.length()-1)!='b'){
classAssignment(n,ans+"b",count);}
}
int main() {
int t;
cin>>t;
for(int i=0;i<t;i++){
int count=0;
int n;
cin>>n;
classAssignment(n,"",count);
cout<<"Total paths are "<<count<<endl;}
return 0;}
Output:
aaa
aab
aba
baa
bab
Total paths are 5
Now I am unable to understand how this code generates this output?? How are these 2 recursive calls are working to get this output??
That's what the debugger is for my friend. The debugger allows you to step through every line of code one by one, and thus, helps us to understand code and also point out errors.
So basically to understand what the recursive calls are doing, let's take an example of the first call. Now the function is first invoked by:
classAssignment(n, "", count);
Remember, ans = "" right now.
Now, the first recursive call:
classAssignment(n,ans+"a",count);
Now when this function is called, ans = "a" (for the recursive function). Now the recursive function calls the above line again, and passes ans + "a" (which means "a" + "a" = "aa") as one of the 2 arguments. Now, ans.size() == n(2), so it is printed out, and both the recursively called functions return, one after the other. Something like this goes for the second recursive call as well.
And if you're wondering for the count variable, all recursive/non-recursive are modifying the same variable, as it's passed by reference.
It may still not be clear but that's the best I could give :). For more clear understanding, you must use the debugger.
By the way, you should really look up to
the reasons Why should I not #include <bits/stdc++.h>?

Void and cout vs int

I was working on an assignment and decided on checking this following problem with my POD. The assignment basically requires a generation of a multiplication problem and loop forever depending on if he gets it right or wrong. So to generate my problem:
int Elementary::setProblem()
{
srand ( time(NULL));
firstfactor = rand() %1;
secondfactor = rand() %1;
answer = factor1 * factor2;
return answer;
}
However, I was told that this method was the proper way of doing:
void Elementary::setProblem()
{
srand ( time(NULL) );
firstfactor = rand()%10;
secondfactor = rand()%10;
answer = firstfactor * secondfactor;
}
She basically told me that answer = is already sets the private member and that return had no use.
Wouldn't my method be faster since I don't have to set the problem and then make a second function to get the problem?
A setter function, typically, does not return anything.
The whole point of pairs of setter and getter functions is that you call one to set something, another to get the value back. That way, you could, for example, completely avoid storing answer, and just calculating it in the getter when you actually need it - in this particular case, this probably gives no benefit, but in some cases, that may be a benefit.

A function that converts base 10 to binary using stacks to solve it

So I'm asked to write this function in C++ that converts a base 10 integer and prints the integer's binary equivalent
I should use a stack to solve the problem also I'm not allowed to use recursion in my function.
Here's what i think:
While doing the conversion i should start pushing the 1s and 0s into a stack accordingly , the order will be reversed (i think) so i will have to move them to another stack to have the right order after doing that i can start taking the top of the copied stack and print it then pop it to get the next number since the function is not a member function and i cant access the members randomly .
I need to know if my method is right and I'm not exactly sure how to do the conversion.
Here you go:-
#include<iostream>
#include<stack>
using namespace std;
int main()
{
int number;
cin>>number;
stack<int> binary;
while(number>1)
{
binary.push(number%2);
number /= 2;
}
cout<<1;
while(!binary.empty())
{
cout<<binary.top();
binary.pop();
}
return 0;
}
Tip:
Whatever recursion can do, loops can also do.
If you have an idea, always try to implement it first. You can still ask questions if you fail.

warning: uninitialized variable //But I have initialized ! C++ Compiler bug?

Iam trying to compile this program but i get warning and when i run vc++ 2010 debugger pops up : (
Here is my code :
#include <iostream>
using namespace std;
int num;
int min(int mas[])
{
int i,minn,index; /* But I have declared them : (((( */
for(i=0;i<num;i++)
{
if(mas[i]!=0)minn=mas[i];
break;
}
if(i==num) return 0;
for(i=0;i<num;i++)
if(mas[i]!=0 && minn>mas[i])
{
minn=mas[i];
index=i;
}
mas[index]=0;
return minn;
}
int main()
{
cin>>num;
int *array=new int[num]; int tmp;
tmp=min(array);
}
and Here is a compiler log :
prog.cpp: In function ‘int min(int*)’:
prog.cpp:6: warning: ‘index’ may be used uninitialized in this function
prog.cpp:6: warning: ‘minn’ may be used uninitialized in this function
What i am doing wrong ? or its is compiler bug ? :)
Thank you :)
You have declared them, but not initialized them. Simply write int minn = 0, index = 0; to avoid the warning. If you don't initialize a variable, its default value is whatever was at that location in memory already; usually garbage.
The thing is, if num is negative, then neither of the for loops in your min() function will execute, and so minn and index will not have been assigned values. The if(i == num) test also won't break out of the function and prevent this from happening. So the last two lines of the function will have completely undefined results.
Sometimes there really isn't a path for the variables to be used uninitialized, though; sometimes the compiler just isn't quite smart enough to figure out all the subtleties. Just give them an initial value to avoid the warning.
Declaration != initialization. When you declare them the variables have random values. Just initialize them to sensible values like -1 for index and minn to a INT_MAX.
But you haven't initialized them : ))))
EX: int i,minn=0,index=0; Imagine that you pass num that equals 0, at the end you would be returning uninitialized value of minn and just before that you would set mas[unknown_number]=0; which will probably cause your app to crash since you will be referencing memory that is most likely beyond your scope. You should do a check in the beggining like if(num<1)return -1;
Suppose the entire array you pass in is 0. Both loops short-circuit and never execute, both minn and index are uninitialized.
Now if this happens, what should be happening? Set the variables to the values that accomplish just that.
As you say in your comment, yes, you have declared your variables, but you haven't initialized them. Initializing a variable means giving it a value. So in this case, you have told the compiler that you want to create three integers, but you haven't told it what values you want to store in those integers. That would be ok if, for every possible path through your function, index and minn were guaranteed to be given a value, but the problem here is that there is a path through your function where minn and index will never be initialized. First of all, here:
for(i=0;i<num;i++)
{
if(mas[i]!=0)minn=mas[i];
break;
}
If you have an array of zeros, then minn is never initialized to a value.
Then further down:
for(i=0;i<num;i++)
if(mas[i]!=0 && minn>mas[i])
{
minn=mas[i];
index=i;
}
first of all, if you had an array of zeros, well what is the value in minn? There is no value. You are asking the compiler to compare mas[i] to a number which doesn't exist. Furthermore, what if mas[i] is always equal to zero? Well now you don't initialize minn or index. Yet at the end of the function, you are attempting to use the value of index to get an integer from the array amd then you return minn (which still equals nothing).
That's the problem you're getting from the compiler. It can see this potential outcome and is warning you that your function can be broken due to these integers never getting a value. To fix it, do what the other lads have suggested and let index and minn equal zero at the start.

C++ clarification of "return"

Homework, just advise please
Apparently my idea of what returning something in a method does is wrong. I'm trying to write methods for getting derivatives of numbers and operations. So far I just wanted to get the derivative of a non-negative number that isn't accompanied with an "x" (result should be zero no matter what value is given).
The code is pretty long and needs to be cleaned up so I'll just include the method, the call, and what I'm getting.
Method:
int noXDerivative(int tempInt, string tempX)
{
if (tempX == "")
{
tempInt = 0;
}
return tempInt;
}
void getDerivatives(int tempInt, string tempX, int tempInt2, string tempX2, char tempOperator)
{
noXDerivative(tempInt, tempX);
noXDerivative(tempInt2, tempX2);
}
The call:
getDerivatives(tempNumInt, tempNumX, tempNum2Int, tempNum2X, expression[iterator]);
I also called the "noXDerivative" directly to see what would happen but the result didn't change. The test I'm running right now is "5 + 6" (tempNumInt is 5 and tempNum2Int is 6). I keep getting 11 when I need to get 0 (again, there are no "x"s). I was hoping that if I put tempNumInt as one of the parameters it would be changed from 5 to 0 within the noXDerivative method but it doesn't. How do I correct this?
I have to say that I don't understand what it is that you're trying to do.
Nevertheless, to achieve your goal of modifying tempInt inside getDerivatives(), you can either do:
tempInt = noXDerivative(tempInt, tempX);
Or, you can modify the noXDerivative() function to take its argument by reference, rather than by value:
int noXDerivative(int &tempInt, string tempX)
{
...
}
return does just that--it returns a value. It doesn't change the value passed in. If I understand your code correctly, I bet that if you had something like
int result1 = noXDerivative(tempInt, tempX)
result1 would hold the value 0. Mind you, tempInt and tempInt2 in getDerivatives won't be modified then, so you'll need to figure that out...
well, not a lot to "advise". The problem here is that when a routine returns a value, the call must be used as a left hand value.
tempInt = noXDerivative(tempInt, tempX);
You will not modify the value of tempInt otherwise, at least with the current signature of your routine. You are passing tempInt as an argument by value with that call, and any modifications you perform to tempInt will occur on the local stack frame of that routine.