Home > Back-end >  Recursion code it not working properly what can be the issue here?
Recursion code it not working properly what can be the issue here?

Time:12-02

Tried a program which prints the first 50 natural number I wrote this code which returns the value using recursion but its not printing anything not returning any values what m I doing wrong here?

#include <stdio.h>

int naturalNumbers(int i)
{
    if (i == 1)
    {
        return 1;
    }
    else
    {
        naturalNumbers(i--);
        return i;
    }
}
                
int main()
{
    printf("%d", naturalNumbers(50));
    return 0;
}

CodePudding user response:

below recursion will print numbers in increasing order

void naturalNumbers(int i)
{
    if(i<1) return; //base case
    naturalNumbers(i-1);
    printf("%d ", i);
}

naturalNumbers(50); // call from main function

CodePudding user response:

To avoid creating an endless loop, you should modify your naturalNumbers function as follows:

int naturalNumbers(int i)
{
    if (i == 1)
    {
        return 1;
    }
    else
    {
        naturalNumbers(--i);
        return i;
    }
}            

This will decrement the value of i before calling naturalNumbers instead of afterwards as in your version. However, the return value of this original call will always be (i-1). Can you please explain a little bit more about the intent of this function?

  •  Tags:  
  • c
  • Related