C program to add n numbers

This c program add n numbers which will be entered by the user. Firstly user will enter a number indicating how many numbers user wishes to add and then user will enter n numbers. In the first c program to add numbers we are not using an array, and using array in the second code.

C programming code

#include <stdio.h>
 
int main()
{
   int n, sum = 0, c, value;
 
   printf("Enter the number of integers you want to add\n");
   scanf("%d", &n);
 
   printf("Enter %d integers\n",n);
 
   for (c = 1; c <= n; c++)
   {
      scanf("%d", &value);
      sum = sum + value;
   }
 
   printf("Sum of entered integers = %d\n",sum);
 
   return 0;
}
You can use long int data type for sum variable.
Output of program:

Add n numbers c program

C programming code using array

#include <stdio.h>
 
int main()
{
   int n, sum = 0, c, array[100];
 
   scanf("%d", &n);
 
   for (c = 0; c < n; c++)
   {
      scanf("%d", &array[c]);
      sum = sum + array[c];
   }
 
   printf("Sum = %d\n",sum);
 
   return 0;
}
The advantage of using array is that we have a record of numbers inputted by user and can use them further in program if required and obviously storing numbers will require additional memory.

Add n numbers using recursion

#include <stdio.h>
 
long calculateSum(int [], int);
 
int main()
{
   int n, c, array[100];
   long result;
 
   scanf("%d", &n);
 
   for (c = 0; c < n; c++)
      scanf("%d", &array[c]);
 
   result = calculateSum(array, n);
 
   printf("Sum = %ld\n", result);
 
   return 0;
}
 
long calculateSum(int a[], int n) {
   static long sum = 0;
 
   if (n == 0)
      return sum;
 
   sum = sum + a[n-1];
 
   return calculateSum(a, --n);
}

No comments:

Post a Comment