1

This my first program of C programming using recursive functions, it calculates the sum of the first n natural numbers. I am not able to get an output from it, it asks for the number but after that the program doesnt respond, can someone please help me out?

int n();

int main(){

    int num;
    printf("Enter num:\n");
    scanf("%d", &num);
    n(num);
    printf("The sum of %d is: %f", num, n(num));
    return 0;
}

int n(int x){

    if (x != 0){
        return n(x) + n(x-1);
**strong text**    }
    else{
        return x;
    }

}
Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
XYZ
  • 25
  • 3

2 Answers2

1

Firstly, in the recursive function, return n(x) + n(x-1); should have been return x + n(x-1); as in the first case, n(x) will continuously make a called to another n(x), therefore making an infinite loop, or, more formally, return a 0xC00000FD exception, a Stack Overflow exception.

Also, in the last printf() function, %f should have been %d:

#include <stdio.h>
int n(int x)
{
    if (x > 0) {return x + n(x-1);} return x;
}

int main()
{

    int num;
    printf("Enter num: ");
    scanf("%d", &num);
    printf("The sum of %d is: %d", num, n(num));
    return 0;
}

Using %f to print an integer will caused an undefined behavior, because %f is a float format specifier, as noted here.

If you really want to convert it to a float:

#include <stdio.h>
int n(int x)
{
    if (x > 0) {return x + n(x-1);} return x;
}

int main()
{

    int num;
    printf("Enter num: ");
    scanf("%d", &num);
    printf("The sum of %d is: %f", num, (double) n(num));
    return 0;
}

*Note: Ran on Code::Blocks 20.03, Windows 10 64bit.

More info on format specifiers : https://www.tutorialspoint.com/format-specifiers-in-c

  • 1
    You probably should explain your actual fix... Clearly OP's code *does not* get to `printf` statement at all... so fixing just that not going to help them much. (Also indeed they just need to copy-paste your answer and delete the question) – Alexei Levenkov May 03 '21 at 02:30
  • @AlexeiLevenkov ah yes, my wrong. I also forgot the error in the recursive function as well. Gonna fix it –  May 03 '21 at 02:32
  • That was it! the x in return. I literally spent a hour looking for the solution! Thank you so much for the detailed explanation :) – XYZ May 03 '21 at 02:43
0
It should be return x instead of calling the same function,
you can use type conversion for changing the integer into a float,

int n();

int main(){

int num,x;
printf("Enter num:\n");
scanf("%d", &num);
x=n(num);
printf("The sum of %d is: %f", num, float(x));
return 0;
 }

int n(int x){

if (x != 0){
    return x + n(x-1);
   **strong text**    }
else{
    return x;
  }

 }
  • He there, welcome to SO. Please read [this](https://stackoverflow.com/help/how-to-ask) page first before asking questions. You may want to format the source code and clearly specify the question you wish to ask. It would help us answer them better. – Unmanned Player May 03 '21 at 08:09