Stack Overflow Asked on February 22, 2021
Note: I am a beginner to the world of C language.
I was trying to write a program that calculates the sum of N natural number.
Here it is:
#include<stdio.h>
int sum_of_N_with_recursion(int N);
int main()
{
int n,result;
do
{
printf("enter a natural number : ");
scanf("%d",&n);
if(n<0)
{
printf("%d is not a natural numbern",n);
}
}while(n<0);
result = sum_of_N_with_recursion(n);
printf("sum of the first %d natural numbers is %dn",n,result);
return 0;
}
int sum_of_N_with_recursion(int N)
{
if(N==0)
{
return 0;
}
return N + sum_of_N_with_recursion(N--);
}
What is my problem?
When I tried to decrement N in the sum_of_N_number() like this sum_of_N_number(N--)
but it doesn’t work. Why?
Example: sum_of_N_number(3)
should equal to 6 but I got 3!!
On this line:
return N + sum_of_N_with_recursion(N--);
You're both reading the value of N
and writing the value of N
in the same expression without a sequence point in between. Attempting to do so is undefined behavior.
You don't actually need to change the value of N
here. You just want to pass in the value N-1
, so do that instead:
return N + sum_of_N_with_recursion(N-1);
Correct answer by dbush on February 22, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP