C Program to add 1 to n numbers

Simple C program to add 1 to n numbers. Here n is input by user. To add 1 to n numbers, there is a math's formula n*(n+1)/2. This formula is used by given program.
#include<stdio.h>
int main()
{
 int n,sum=0;
 printf("Enter A number: ");
 scanf("%d",&n);
 sum=sum+(n*(n+1))/2;
 printf("Sum of 1 to %d numbers= %d ",n,sum);
 return 0;
}
C program to add 1 to n numbers using while loop
#include<stdio.h>
int main()
{
 int a,n,sum=0;
 printf("Enter a number: ");
 scanf("%d",&n);
 a=n;
 while(n!=0)
 {
  sum=sum+n;
  n--;
 }
 printf("Sum of 1 to %d numbers= %d ",a,sum);
 return 0;
}
C program to add 1 to n numbers using recursion
#include<stdio.h>
int AddNumbers(int n)
{
 int sum=0;
 if(n==0)
 {
  return 0;
 }
 else
 {
  return n+AddNumbers(n-1);
 }
}
int main()
{
 int n,sum;
 printf("Enter A number: ");
 scanf("%d",&n);
 sum=AddNumbers(n);
 printf("Sum of 1 to %d numbers= %d ",n,sum);
 return 0;
}

Popular posts from this blog