C++ recursion example explanation - c++

I have the following code example and I cannot figure out why it displays 123.
Since these are integers I understand the decimals are not displayed. But I expected it to show 3, 2(.3), 1(.23) (in the opposite order). When n goes below 10 everything stops after the final cout... right?
#include <iostream>
using namespace std;
void recursion(int n) {
if (n < 10) cout << n;
else {
recursion(n / 10);
cout << n % 10;
}
}
int main() {
recursion(123);
return 0;
}

Well, you call with 123 as n, the function executes the statement:
if (n < 10) // its false, so it continues with else:
else {
recursion ( n /10 ) // recursive call n/10 = 123/10 = 12 (as it's int)
...
It will continue like this, recursively calling with n being 12
recursion (n/10) // second recursion call n=12, so n/10 = 1
then the function is executed, with n being 1 so smaller than 10
if (n < 10) // its true
cout << n; // 1 gets printed
else // no, the rest is skiped
...
then it returns from recursion. So we're back in the context where n was 12. The next statement to be executed in that context is :
cout << n %10; // prints 12 % 10, which is 2
then, continuing like this, similarly it will print 123%10, which is 3. In conclusion, the 123 that is printed has nothing to do with the 123 entered as input.
I think you wanted to do :
...
else {
cout << n % 10; // first print to see the count down
recursion(n / 10); // then recurse
}
But you have to learn using a debugger. As long as you don't, put some extra cout to visualize what's happening.

Related

C++ , cout line in function effects the result, function does not work without cout line

I'm trying to solve Codewars task and facing issue that looks strange to me.
Codewars task is to write function digital_root(n) that sums digits of n until the end result has only 1 digit in it.
Example: 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6 (the function returns 6).
I wrote some bulky code with supporting functions, please see code with notes below.
The problem - digital_root function works only if I put cout line in while loop. The function returns nonsense without this cout line (please see notes in the code of the function).
My questions are:
Why isn't digital_root working without cout line?
How cout line can effect the result of the function?
Why does cout line fix the code?
Thanks a lot in advance! I'm a beginner, spent several days trying to solve the issue.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int getDigit (int, int);
int sumDigits (int);
int digital_root (int);
int main()
{
cout << digital_root (942); // expected output result is 6 because 9 + 4 + 2 = 15 -> 1 + 5 = 6
}
int getDigit (int inputNum, int position) // returns digit of inputNum that sits on a particular position (works)
{
int empoweredTen = pow(10, position-1);
return inputNum / empoweredTen % 10;
}
int sumDigits (int inputNum) // returns sum of digits of inputNum (works)
{
int sum;
int inLen = to_string(inputNum).length();
int i = inLen;
while (inLen --)
{
sum += getDigit(inputNum, i);
i --;
}
return sum;
}
int digital_root (int inputNum) // supposed to calculate sum of digits until number has 1 digit in it (abnormal behavior)
{
int n = inputNum;
while (n > 9)
{
n = sumDigits(n);
cout << "The current n is: " << n << endl; // !!! function doesn't work without this line !!!
}
return n;
}
I've tried to rewrite the code from scratch several times with Google to find a mistake but I can't see it. I expect digital_root() to work without any cout lines in it. Currently, if I delete cout line from while loop in digital_root(), the function returns -2147483647 after 13 seconds of calculations. Sad.
Here is an implementation using integer operators instead of calling std::to_string() and std::pow() functions - this actually works with floating-point numbers. It uses two integer variables, nSum and nRem, holding the running sum and remainder of the input number.
// calculates sum of digits until number has 1 digit in it
int digital_root(int inputNum)
{
while (inputNum > 9)
{
int nRem = inputNum, nSum = 0;
do // checking nRem after the loop avoids one comparison operation (1st check would always evaluate to true)
{
nSum += nRem % 10;
nRem /= 10;
} while (nRem > 9);
inputNum = nSum + nRem;
std::cout << "The current Sum is: " << inputNum << endl; // DEBUG - Please remove this
}
return inputNum;
}
As for the original code, the problem was the uninitialized sum variable, as already pointed out by other members - it even generates a compiler error.
int sumDigits (int inputNum) // returns sum of digits of inputNum (works)
{
int sum = 0; // MAKE SURE YOU INITIALIZE THIS TO 0 BEFORE ADDING VALUES TO IT!
int inLen = to_string(inputNum).length();
int i = inLen;
while (inLen --)
{
sum += getDigit(inputNum, i);
i --;
}
return sum;
}
Initialize your variables before adding values to them, otherwise you could run into undefined behaviour. Also for the record, adding the cout line printed out something, but it wasn't the correct answer.

why am I getiing 0 as a result,I want the return value as the result?

I want the result to be the returned value from the mystery function,but the result is always 0 .but I want the program to return a value that's collected from the mystery function
#include <iostream>
using namespace std;
int Mystery(int n)
{
// int k;
if (n <= 1)
{
return 0;
}
else
{
int k = n;
for (int i = 1; i <= n; i++)
{
k = k + 5;
}
cout << ((k * (n / 2)) + (8 * (n / 4)));
cout << "\n ";
return ((k * Mystery(n / 2)) + (8 * Mystery(n / 4)));
}
}
int main(void)
{
int i, n;
cout << "Enter n:"; //array size
cin >> n;
int result = Mystery(n);
cout << "The result is " << result;
return 0;
}
Let's desk check what happens when you call Mystery(2). The final return value is:
((k* Mystery(n/2)) + (8* Mystery(n/4)))
We know that n == 2 so let's substitute that:
((k* Mystery(1)) + (8* Mystery(0 /* by integer division of 2/4 */)))
This will call the function recursively twice with the respective arguments 1 and 0. But we know that the terminating case n <= 1 returns 0, so we can substitute that:
((k* 0) + (8* 0))
Anything multiplied by zero is zero, so this reduces to 0 + 0 which is also zero. It doesn't even matter what k is.
Quite simply, the terminating case for this recursion mandates that the result is always zero.
In the terminating case the return value is zero.
In the recursive case, the recursive call result is multiplied with another value to produce the return value.
Therefore, the result is always going to be zero for any n.
I'm not sure exactly how this function is supposed to work as you have not explained that, but changing the terminating case to return 1; may solve the problem.
I don't expect which result you want, but I think you can get write result when you correct conditions like
if (n == 0)
return 0;
if (n == 1)
return 1;
I hope it returns the right result.

Using recursion to reverse an integer without trailing 0's in C++

I am stuck on how to omit trailing zeros, on a recursive call to reverse an integer. If you could just guide me to the right path I'd appreciate it. I am stuck and do not know how to do it. I have came this far, but am struggling to complete it. Thanks.
int main() {
int numToReverse;
cout << "Please enter in a number: " << endl;
cin >> numToReverse;
cout << reverseIntRecursion(numToReverse) << endl;
}
int reverseIntRecursion(int n) {
if (n < 10) //Base Case
return n;
else
cout << n % 10; // Prints out the last number
return reverseIntRecursion(n / 10); // General Case, Recursive Function
}
Maybe easiest way is parse int to string (array of chars) and print as array?
Here is some code that works just fine as long as you enter true for the second parameter:
int ReverseIntRecursion(int, bool);
int main(int argc, const char * argv[]) {
std::cout << ReverseIntRecursion(30400, true);
std::cout << std::endl;
return 0;
}
int ReverseIntRecursion(int N, bool FirstIter)
{
if (N < 10)
return N;
else if (N % 10 == 0 && FirstIter)
return ReverseIntRecursion(N/10, true);
else
std::cout << (N % 10);
return ReverseIntRecursion(N/10, false);
}
// prints 403
Your function isn't reversing an integer. It just prints digits in a reverse order.
This is why you are getting your trailing zeros problem. If you wrote a function which actually reversed the integer - your problem would disappear.
For example:
// Helper function for reversing an integer.
int reverseIntRecursionBase(int n, int& base) {
if (n < 10) // trivial case. If n consists of a single digit - reversed n is equal to n.
{
return n;
}
int result = reverseIntRecursionBase (n/10, base); // recurse until you hit a trivial case.
/*
The leftmost digits in the original number should be the
rightmost digits in the reversed number.
This code will be first executed, after trivial case has been hit:
e.g. given number 1234, this line will be first reached when n = 12; result = 1.
*/
base *= 10;
result = (n % 10)*base + result;
return result;
}
int reverseIntRecursion(int n) {
int base = 1;
return reverseIntRecursionBase (n, base);
}
Live demo.

Dividing an even number in the most efficient way

I need a program in c++ that gets a number:
LOOP:
If that number is even divide it by 2 (n=n/2)
If it's not even you can do one of this operations:
n+1
n-1
LOOP ENDS
The program should do this until n=1.
But it should do this in the most efficient and fastest way and the only hint I have is that I can use DP approach.
And the output should be numbers of operations used to calculate that number.
For example:
15->16->8->4->2->1 output:5
35->36->18->9->8->4->2->1 output:7
here's the code I wrote but it's not completed yet and it's wrong since I couldn't figure out how should I add or subtract in each step:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int n;
int h=0;
int i=0;
cout<<"Enter A Number:";
cin >> n;
int r=n;
int q=n;
cout<<r;
L1: while ( r % 2 == 0)
{
for(int m=0;r>1 && m==0 ;)
{ r=r / 2;h++;
m=r%2;
cout<<" => "<<r;
}}
while(r%2==1 && r>1)
{r=r-1;cout<<" => "<<r;h++;
goto L1;}
cout<<endl;
//**********************
cout<<q;
L2: while ( q % 2 == 0)
{
for(int m=0;q>1 && m==0 ;)
{ q=q / 2;i++;
m=q%2;
cout<<" => "<<q;
}}
while(q%2==1 && q>1)
{q=q+1;cout<<" => "<<q;i++;
goto L2;}
cout<<endl<<"First:"<<h<<endl<<"Second:"<<i<<endl;
system("pause");
}
If you want to solve it using DP:
I would state this: for each possible value 1 <=i < N find the optimal number of steps.
We use a priority queue to do this where we extract at each iteration the highest number. This is much more efficient than a vector of length N because a lot of states are unreachable (e.g. i=10 in the 15 example).
Consider that the starting state is (15,0): 15 with zero moves.
From this you create two new states (8,2) and (7,2) because for each you need two steps(add/subtract + division).
Extracting (8,2): (7,2)(4,3)
Extracting (7,2): (4,3)(3,4) Here comes DP! (7,2) would create the state (4,4) but you mantain in the queue only the minimum number of steps for the same state.
Extracting (4,3): (2,4)(3,4)
extracting(3,4): (2,4)(1,6)
Extracting (2,4): (1,5)
And that is it the solution is 5 steps.
Steps for 35:
(35,0) --- >(18,2) (17,2) -----> (17,2) (9,3) ----->
(9,3)(8,4) ----> (8,4)(5,5)(4,5) ----> (5,5)(4,5) ----->
(4,5)(3,7)(2,7)----> (3,7)(2,6) -----> (2,6)(1,9) ----> (1,7)
Solution: 7 steps.
Look if that helps you.
// Example program
#include <iostream>
#include <string>
int f (int n)
{
int iterations = 0;
while (n > 1)
{
if (n % 2 != 0)
{
std::cout << n << "->";
++n;
if (n & (n - 1))
n -= 2;
++iterations;
}
std::cout << n << "->";
n >>= 1;
++iterations;
}
std::cout << n << "->";
return iterations;
}
int main()
{
std::cout << f(15) << std::endl;
std::cout << f(41) << std::endl;
std::cout << f(43) << std::endl;
}
For use of dynamic programming, you should make recursion to get sub-solutions to the problem and then solve the problem itself. You also have to use a memory structure to hold the results of such sub-solutions.
#include <deque>
#include <iostream>
using namespace std;
int solve(deque<int>& solution, int number) {
if(number >= solution.size()) // resize to fit
solution.resize(number + 1, -1);
if(number == 1) // special case for number 1
return solution[number] = 0;
if(solution[number] != -1) // if already calculated
return solution[number];
if(number % 2 == 0) // n=n/2
return solution[number] = solve(solution, number/2) + 1;
int solutionA = solve(solution, number + 1); // n++
int solutionB = solve(solution, number - 1); // n--
return solution[number] = std::min(solutionA, solutionB) + 1; // best of n++,n--
}
int main() {
deque<int> solution;
cout << solve(solution, 35);
}
I'm not sure the code will work though.
Here's my recursive solution, verified up to 2097152 against the DP example.
The basis of it is using the value of the last two bits to determine the optimal operation. If the last bit is a 0, we always divide. If the last two bits are 11 we always increment as this transforms to 100 which enables two consecutive divide operations.
If the last two bits are 01 we decrement as this gives our next operation two consecutive divide operations vs incrementing which gives us 10.
The corner case is the number 3 where 3 -> 2 is desired over promotion to 4.
I suspect you can optimise this further by just scanning the bit pattern to determine the number of operations required. i.e. each zero requires a div op, and a set of ones can be changed into zeroes with a single addition.
#include <cstdint>
int solve_algorithmically(std::uint64_t number)
{
// If 1 there is nothing to do.
if (number <= 1)
return 0;
// Nasty hack to get around the case where number=3 & 3 == 3 will cause increment
if (number == 3)
return solve_algorithmically(number - 1) + 1;
// If we have an even number (0 in LSB)
if ((number & 1) == 0)
return solve_algorithmically(number / 2) + 1;
// If we have two consecutive 1's i.e. (...11) then increment as this wil give us two zeroes.
// The exception is the root case 3 where decrement wins.
if ((number & 3) == 3)
return solve_algorithmically(number + 1) + 1;
// The only other case ends last two bits = 01
return solve_algorithmically(number - 1) + 1;
}
int main() {
for (auto i = 1; i < 2097152; i++)
{
int alg = solve_algorithmically(i);
}
}

Can't print Fibonacci series

I was writing a small snippet to get a Fibonacci number sequence depending on the user input. If the user supplies 4 as an input, it should return him the first N members of the Fibonacci sequence.
#include <iostream>
using namespace std;
int main (){
int a = 0;
int b = 1;
int c;
int n = 3;
n -= 2;
if (n == 1){
cout << a << endl;
} else {
cout << a << b << endl;
for (int i=0;i<n;i++){
c = b + a;
cout << c << endl;
a = b;
b = c;
}
}
}
However, I end up getting a 0 as an output for whatever number I supply. I have this working in PHP and I kinda miss where I've blundered. I guess I don't actually render input and output properly.
int a =0;
int n = 3;
n -= 2;
if (n == 1){
cout << a << endl;
}
You have n equal to 3, you subtract 2, thus n equal to 1, so, you enter the if body and output a, which is zero.
[EDIT]
You don't seem to get any input -as stated in a comment- in your program (you could use std::cin or std::getline() for this), but you probably mean that you have the input hard-coded, by changing the value of n by hand.
You may want to check how the Fibonacci series program is expected to work:
Fib. at Rosseta page.
Fib. with recursion
Non-recursive Fib.
After reading the links I provided above, you should be able to see that your code should be changed to this:
#include <iostream>
using namespace std;
int main (){
int a = 1;
int b = 0;
int c;
int n = 10; // "input" is 10
if (n == 0 || n == 1) { // 0 and 1 case
cout << n << endl;
} else {
for (int i = 2; i <= n; ++i) { // here you want to reach n
c = a + b;
b = a;
a = c;
}
cout << c << endl;
}
return 0;
}
However, the code above outputs only the result. You should slightly modify it to get the terms of the sequence, but I'll leave you have some fun too.
In order to really let the user input the number, change:
int n = 10;
to
int n;
std::cout << "Please, input.\n";
std::cin >> n;
However, letting user inputting must be followed by validation of the input. You see users can, by accident or not, provide input in your program, that can cause undefined behaviour.
The sequence you want is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...
As I pointed out in a comment to another answer, your code does not produce a correct Fibonacci sequence. F(3) isn't the problem with your code; the problem is that you get confused between all the variables, a, b, c and use them to mean different things at once.
You also incorrectly decrement n: your code does it in the wrong place, and even if you move it to the right place, it wouldn't help as the operation would make n go negative.
Your existing Code
Let's walk through your code a bit:
int a = 0;
int b = 1;
int c;
int n = 3;
n -= 2;
Well, this is weird. We set n to 3 then immediately subtract 2, making it 1. This means that if you try to set n to 0, 1, or 2 you end up with n being a negative number. If you set it to 3, you end up with n being 1.
if (n == 1){
cout << a << endl;
}
We're in trouble right here. Remember that you subtract 2 from n which means that for n==3 you will return whatever is in a which is wrong. But even if you meant this to special-case F(1) that code is still wrong because F(1)=1.
else {
cout << a << b << endl;
for (int i=0;i<n;i++){
Remember, that we can get here with n zero or negative. Obviously in the case of n <= 0 this loop will never execute, so c will never be printed.
c = b + a;
cout << c << endl;
Here, we seem to calculate and output the next Fibonacci number by adding the two previous numbers. This should be fine.
a = b;
b = c;
And here, we keep the new Fibonacci number and its predecessor for the next loop iteration, if any.
The problems with this code are, of course, fixable. But the problem is that the existing code is confusing. It outputs all sorts of different values, and it's unclear what variable is supposed to represent.
Looking at this problem, your first instinct would be to make a function which accepts as input a number n and returns F(n) - you could call it fib or somesuch.
Reworking this
So, how to go about writing such a function? Here's a simple recursive implementation that you can use:
int fib(int n)
{
if ((n == 0) || (n == 1))
return n;
return fib(n-1) + fib(n-2);
}
Notice how this function is short, sweet and to the point. There's no need for a ton of variables, no need for complicated control structures or storing state. It almost reads like a text-based description of the Fibonacci algorithm.
Of course, it's not super-efficient and ends up redoing a lot of work. That's a legitimate criticism, but it's unlikely that there performance considerations here.
Still, perhaps you just don't like recursion. Many people think of recursion as a dirty word, and avoid it with a passion. So how about a non-recursive implementation instead? It's possible, but it's a bit more difficult to understand.
int fib (int n)
{
/* F(0) = 0 */
if (n == 0)
return 0;
int a = 0;
int b = 1;
for (int i = 2; i < n; i++)
{
int c = a + b;
a = b;
b = c;
}
/* F(n) = F(n-2) + F(n-1) */
return a + b;
}
This is a little bit more efficient and not that much more difficult to understand.
I hope that this helped.
Try this which would give you the list you needed.
#include <iostream>
using namespace std;
int fib(int num){
int ans;
if (num >2) {
ans = fib(num-1) + fib(num-2);
}
else
ans = 1;
return ans;
}
int main()
{
int num, x=1;
cin >> num;
while (num >= x) {
cout << fib(x) <<" ";
x++;
}
return 0;
}