C Program to add n numbers

Simple C program to add n numbers.
#include<stdio.h>
int main()
{
 int n,i=1,sum=0;
 printf("How many do you want to add: ");
 scanf("%d",&n);
 while(i<=n)
 {
  int num;
  printf("Enter %d number: ",i);
  scanf("%d",&num);
  sum=sum+num;
  i++;
 }
 printf("Sum of %d numbers = %d",n,sum);
 return 0;
}
C program to add n numbers using recursion
#include<stdio.h>
int SumOfNumbers(int n)
{
 int sum=0;
 if(n==0)
 {
  return 0;
 }
 else
 {
  int num;
  printf("Enter number: ");
  scanf("%d",&num);
  return sum+num+SumOfNumbers(n-1);
 }
}
int main()
{
 int n,sum;
 printf("How many do you want to add: ");
 scanf("%d",&n);
 sum=SumOfNumbers(n);
 printf("Sum of %d numbers= %d",n,sum);
 return 0;
}




Popular posts from this blog