C code to find the addition of n numbers by recursion:
#include<stdio.h>
int main(){
int n,sum;
printf("Enter the value of n: ");
scanf("%d",&n);
sum = getSum(n);
printf("Sum of n numbers: %d",sum);
return 0;
}
int getSum(n){
static int sum=0;
if(n>0){
sum = sum + n;
getSum(n-1);
}
return sum;
}
Sample output:
Enter the value of n: 10
Sum of n numbers: 55
C code to find the addition of n numbers without using recursion:
#include<stdio.h>
int main(){
int n,sum;
printf("Enter the value of n: ");
scanf("%d",&n);
sum = getSum(n);
printf("Sum of n numbers: %d",sum);
return 0;
}
int getSum(n){
int sum=0;
while(n>0){
sum = sum + n;
n--;
}
return sum;
}
No comments:
Post a Comment