C Program to print sum of array elements

Category: C ProgramTags: array cprogram

C Program to print the sum of array elements using loop and recursion.

C Program to print sum of array elements using loop

#include <stdio.h>

void main()
{
    int n, i, arr[50], sum = 0;
    printf("Enter number of elements: ");
    scanf("%d", &n);

    printf("Enter array elements -\n");
    for (i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    for (i = 0; i < n; i++)
        sum = sum + arr[i];

    printf("Sum of array elements: %d", sum);
}

C Program to print sum of array elements using recursion

#include <stdio.h>

int printSum(int arr[], int start, int end)
{
    if (start >= end)
        return 0;
    return arr[start] + printSum(arr, start+1, end);
}

void main()
{
    int n, i, arr[50], sum = 0, sumOfArray;
    printf("Enter number of elements: ");
    scanf("%d", &n);

    printf("Enter array elements -\n");
    for (i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    for (i = 0; i < n; i++)
        sum = sum + arr[i];

    sumOfArray = printSum(arr, 0, n-1);
    printf("Sum of array elements: %d", sum);
}

Output

Output

Enter number of elements: 5
Enter array elements -
1
2
3
4
5
Sum of array elements: 15