Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c recursion program problem

I'm new to concept of recursion. I want to write a recursive function which take a float and integer as argument and call it recursively in a way that the float value remain constant and integer value changes

I write the following code:

#include <stdio.h>

float sum(float f, int k)
{
    static float c;
    c = f - k;
    c = sum(f, k - 1);
    return c;
}

int main()
{
    float f, g = 10.00;
    int i = 5;
    f = sum(g, i);
    printf("the sum of integer and float = %f", f);
}

When I compile it it shows no errors but when I run the program it shows a segmentation fault.

My question are following:

  1. what is wrong with the code?
  2. why it is showing segmentation error?
  3. how to use recursion in a function which has more than one argument?

Please explain me with some example of recursive function which has two arguments.

like image 893
Golu Avatar asked Apr 20 '26 04:04

Golu


1 Answers

The code is wrong because it can never end (I presume it fails with a stackoverflow error).

For recursion, you need two things

  1. A base case
  2. A recursive case that moves towards the base case

Looks like you've only got the second. I suspect sum should return when k is zero. Something like this hopefully makes sense:

 float sum(float f, int k) {
     if (k <= 0) {
         // The base case
         return f;
     } else {
         // The recursive case.  This does one step of the work
         // and moves towards the base case
         return 1 + sum(f, k - 1);
     }
 }
like image 131
Jeff Foster Avatar answered Apr 21 '26 16:04

Jeff Foster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!