## INDEX

### Sum of n numbers using recursion in c

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;
}

Alogrithm:

Sum of n numbers using recursion in c
Matrix multiplication using recursion in c
Multiplication using recursion in c
Lcm using recursion in c
Using recursion in c find the largest element in an array
Prime number program in c using recursion
Decimal to binary conversion in c using recursion
C program for fibonacci series using recursion
Reverse a string using recursion
Write a program for palindrome using recursion
Find factorial of a number using recursion in c program
Find gcd of a number using recursion in c program
Find sum of digits of a number using recursion using cprogram
Find power of a number using recursion using c program
Binary search through recurssion using c program
Reverse a number using recursion in c program
Big list of c program examples

deepak said...

This is the program for additiion of n consecutive numbers starting from 1.

Anonymous said...

The recursion program to add consecutive n numbers starting from 1 (without using static variables):
int getSum(int n)
{
if(n == 1)
return 1;

return (n + getSum(n-1));
}

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;
}

Anonymous said...

@Anonymous your code does not work with negative numbers:
better getSum function would be to add if block:

int getSum(int n)
{
if(n == 1)
return 1;
else if(
return (n + getSum(n-1));
}

mine too, it works only for non negative numbers, i mean we cannot get sum of negative numbers from my algorithm.

natia ebralidze said...

could you please tell me if my code will work as well? or what is side effects that I wrote 0 and you guys 1