Sum of n numbers in C

Sum of n numbers in C: This program adds n numbers which will be entered by a user. The user will enter a number indicating how many numbers to add and then the user will enter n numbers. We can do this by using or without using an array.

C program to sum n numbers using a for loop

#include<stdio.h>
#include<conio.h> 
void main()
{
  int n, sum = 0, c, value;
 
  printf("How many numbers you want to add?\n");
  scanf("%d", &n);
 
  printf("Enter %d integers\n", n);
 
  for (= 1; c <= n; c++)
  {
    scanf("%d", &value);
    sum = sum + value;
  }
 
  printf("Sum of the integers = %d\n", sum);
 
  getch();
}


C program to calculate sum of n numbers using an array

#include<stdio.h>
#include<conio.h>
void main()
{
   int n, sum = 0, c, array[100];
   scanf("%d", &n);
   for (= 0; c < n; c++)
   {
      scanf("%d", &array[c]);
      sum = sum + array[c];
   }
   printf("Sum = %d\n", sum);
    getch();
}

C program for addition of n numbers using recursion

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

No comments:

Post a Comment