Imposter
Imposter

Reputation: 2686

missed logic in finding sum using recurssion ,got segfault

I tried to achieve following using recurssion but im getting segfault pls correct me??

i tried solving problem using permutation of set {1,,3,5,7} but failed to output the required result print all compositions of a number in odd parts, i.e. for n = 8: 7 + 1
5 + 3
5 + 1 + 1 + 1
3 + 3 + 1 + 1
3 + 1 + 1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1

sumto8(a,start,sum1) is://choosing element of concern sumto8(a,start,sum)is ://choosing element of concern

#include<iostream>
#include<stdio.h>

int sumto8(int*,int,int);
int n=4;
int c=8;

int main()
{
    int a[]={1,3,5,7};
    sumto8(a,0,c);
}

int sumto8(int* a,int start,int sum)
{
   if((sum<0) || (start>(n-1)))
   return -1;

   if(sum==0)
   {
       cout<<" "<<a[start];
       return printf("+ %d",a[start]);
   }
   if(i==-1)
      {
       return-1;
      }
      if(j==-1)
      { 
        return -1
      }




   else
   {
      int sum1=sum-a[start];


      int i=sumto8(a,start,sum1);



      int j=sumto8(a,start+1,sum);
   }

   return printf("+ %d",a[start]);
}

it seems the if condition for sum<0 is not checking properly...

output :segfault

Upvotes: 0

Views: 167

Answers (2)

Oki Sallata
Oki Sallata

Reputation: 374

you say

it seems the if condition for sum<0 is not checking properly...

i found out that your checking like this

   if((sum<0) && (start>(n-1)))
   return -1;

how if the "and" you change it to "or"

   if((sum<0) || (start>(n-1)))
   return -1;

Upvotes: 2

seanwatson
seanwatson

Reputation: 1083

I've found one problem with the nested for loop within main. It should read for(int j=0; j<c; j++). You have it as j<c+1 which will go outside the bounds of the array as you have declared it

edit: there is another problem with this section:

    /*dp[start][sum1]=*/sumto8(a,start,sum1);//choosing element of concern 
    start++;
    /*dp[start][sum]*/=sumto8(a,start,sum);

In the second call to sumto8 you haven't commented out the =. You have a lot of blank space and commented code. You also never call the isVisited() function the way everything is commented right now and at the end of the sumto8 function you have two identical return statements at the end. It would really help if both yourself and everyone here if you cleaned it up a bit.

Upvotes: 1

Related Questions