Home > Software design >  Does not iterate in recursion
Does not iterate in recursion

Time:09-17

I have made a code to solve a problem. This is the link of problem: https://brilliant.org/practice/bijections-overview/?p=2 My opinion is use recursion. I have 3 elements to sum up 5, I iterate single element from 0 to 5 and so on.

This is my code:

#include<bits/stdc  .h>
using namespace std;

int count_sum_5(int sum, int n)
{   
    if(n == 1) return 1;
    for(int i = 0; i <= sum ; i  ){
        return 1   count_sum_5(sum - i, n - 1);
    }
}

int main()
{
    int sum = 5;
    int count_ele = 3;
    cout << count_sum_5(sum, count_ele);
}

Its output is 3, I think it only runs on i = 0 but does not run on i = 1, 2, 3, 4, 5. Could you help me?

CodePudding user response:

return evaluates 1 count_sum_5(sum - i, n - 1) and then immediately exits the whole function, on the first iteration of the loop. It's not possible to return from a function multiple times.

CodePudding user response:

I don't know what exactly are you trying to solve using that. But For loop will run only one time for i=0, because as soon as it evaluates the 1 count_sum(sum-i, n-1), It will return it.

However, you can do the following changes:

#include<bits/stdc  .h>
using namespace std;

int count_sum_5(int sum, int n)
{   
    if(n == 1) return 1;
    int temp = 0;
    for(int i = 0; i <= sum ; i  ){
        temp  = (1   count_sum_5(sum - i, n - 1));
    }
    return temp;
}

int main()
{
    int sum = 5
    int count_ele = 3;
    cout << count_sum_5(sum, count_ele);
}

CodePudding user response:

Your function will return 1 if n is 1. Otherwise it will enter the for cycle, which will return the value of the first iteration. You call your function by passing 5 and 3, respectively.

First call: It returns 1 count_sum_5(5, 2)

Second call: It returns 1 count_sum_5(5, 1)

Third call: It returns 1

So, the second call will evaluate to 1 1 = 2 and then the second call will evaluate to 1 2 = 3. I'm not sure what your intention is, but the for cycle is not needed for your recursion. Your function is equivalent to

int count_sum_5(int sum, int n)
{   
    if(n == 1) return 1;
    return 1   count_sum_5(sum, n - 1);
}

I'm not sure whether you are satisfied with this. If not, then please let me know what you intend to achieve, sample inputs and outputs would help. If you provide further information, then I will edit my answer accordingly.

  • Related