Why this code generate segmentation fault? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why this code generate segmentation fault?

#include<stdio.h> int sum(int a) {int b; if(a==1) { return 1; } else return b=sum(a+sum(a-1)); } int main() {int num; printf("Enter a number for sum:"); int num; scanf("%d",&num); int res=0; res=sum(num); printf("SUM : %d",res); return 0; }

22nd Nov 2022, 7:35 AM
Pavan Rajak
Pavan Rajak - avatar
1 Answer
+ 4
Pavan Rajak You have declared b inside sum method and assigned value so working till infinite time so what you are trying to do? many mistakes in your logic: #include<stdio.h> int sum(int a) { //int b; if(a == 1) return 1; else return a + sum(a - 1); } int main() { printf("Enter a number for sum:"); int num; scanf("%d",&num); int res=sum(num); printf("SUM : %d",res); return 0; }
22nd Nov 2022, 8:04 AM
A͢J
A͢J - avatar