Function Assignment 20 — Calculate the Sum of Elements in an Array Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Calculate the Sum of Elements in an Array Using a Function

📑 On this page:
  • The running-total pattern
  • Designing the arraySum function
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How the running-total pattern works — initialize to 0, add each element
  • Why 0 is the "additive identity" and the right starting value for sums
  • How to avoid integer overflow by using long long
  • How to compute averages and other statistics from the sum
  • Why the sum is a "reduction" — and how it relates to min, max, and other operations

The running-total pattern

Summing an array is one of the simplest yet most foundational algorithms in programming. You start with a running total of 0, then walk through the array and add each element to the total. When you're done, the total holds the sum. That's it — three lines of logic, no edge cases beyond empty arrays (which correctly sum to 0), and no tricky conditions.

The key insight is that 0 is the additive identity — adding 0 to any number leaves it unchanged. Starting the sum at 0 means the first iteration computes 0 + arr[0] = arr[0], the second computes arr[0] + arr[1], and so on. Each iteration is "the sum of everything seen so far," building up incrementally. This is the same shape as the running-max and running-min patterns — initialize to the identity value, fold each element in, return the accumulated result.

Summing is the simplest example of a reduction: taking a sequence of values and reducing it to a single value. Many operations are reductions — max, min, sum, product, count, average, and more. They all follow the same pattern: pick an accumulator value, iterate, update the accumulator. The specific accumulator and update rule differ, but the loop structure is identical. Recognizing this shape is a gateway to a whole family of useful algorithms.

One practical consideration: overflow. The sum of many integers can exceed the range of int quickly. Ten INT_MAX values alone overflow. So for a general-purpose sum function, use long long as the accumulator and return type — it can hold sums up to about 9.2 quintillion, which is enough for any realistic array. This is a small but important defensive choice that prevents a whole class of subtle bugs.

💡 In one line: set total = 0, then for each element, total += arr[i]. Return total. For an empty array, the loop doesn't run and the function correctly returns 0.

A row of numbers with arrows adding each one into an accumulator, showing the running total increasing.

Designing the arraySum function

The signature is essentially the same as the min/max functions, with one important change — the return type:

Part Choice Why
Function namearraySumDescriptive. Alternatives: sumArray, total.
Array parameterconst int arr[]Read-only. The compiler prevents any modification.
Size parameterint nRequired because arrays decay to pointers.
Return typelong longLarger than int, so the sum can grow without overflow. If int were used, a few hundred large values would overflow.

The prototype:

long long arraySum(const int arr[], int n);
                                

And the definition:

long long arraySum(const int arr[], int n) {
    long long total = 0;
    for (int i = 0; i < n; i++) {
        total += arr[i];
    }
    return total;
}
                                

Notice the accumulator is long long even though the array elements are int. When we do total += arr[i], the int value is promoted to long long before the addition, so the sum accumulates in the wider type. This is exactly what we want — each individual element fits in int, but the sum might not.

And a version that also computes the average, which is often the natural next step:

double arrayAverage(const int arr[], int n) {
    if (n == 0) return 0.0;
    return (double)arraySum(arr, n) / n;
}
                                

The cast (double)arraySum(arr, n) is essential. Without it, the division would be long long / int, which does integer division — truncating to the nearest whole number. With the cast, the division happens in double, preserving the fractional part. This is a common source of bugs in "average" functions.

And here's a version that uses a pointer instead of an index, which is arguably more idiomatic C:

long long arraySum(const int *arr, int n) {
    long long total = 0;
    for (int i = 0; i < n; i++) {
        total += arr[i];
    }
    return total;
}
                                

Functionally identical — int arr[] and int *arr are the same in a function parameter list. Use whichever reads better to you.

🎯 Key idea: sum is the simplest reduction — initialize to the identity (0), combine each element with the accumulator (using +=), return the result. Max, min, product, count — they're all the same shape with different identities and combine operations.

Complete C Program

Program: read an array, compute the sum

#include <stdio.h>

/* Function prototype */
long long arraySum(const int arr[], int n);

int main(void) {
    int arr[100];
    int n;

    printf("How many elements? ");
    if (scanf("%d", &n) != 1 || n <= 0 || n > 100) {
        printf("Please enter a valid count between 1 and 100.\n");
        return 1;
    }

    printf("Enter %d integers: ", n);
    for (int i = 0; i < n; i++) {
        if (scanf("%d", &arr[i]) != 1) {
            printf("Invalid input.\n");
            return 1;
        }
    }

    long long total = arraySum(arr, n);
    printf("Sum: %lld\n", total);
    printf("Average: %.2f\n", (double)total / n);

    return 0;
}

/* Sum all elements */
long long arraySum(const int arr[], int n) {
    long long total = 0;
    for (int i = 0; i < n; i++) {
        total += arr[i];
    }
    return total;
}
                                    

And a version that counts even and odd elements alongside the sum — showing how multiple reductions can share a loop:

Variant: sum, count, and average in one pass

#include <stdio.h>

void analyze(const int arr[], int n,
             long long *outSum, int *outEvens, int *outOdds) {
    long long sum = 0;
    int evens = 0, odds = 0;

    for (int i = 0; i < n; i++) {
        sum += arr[i];
        if (arr[i] % 2 == 0) evens++;
        else odds++;
    }

    *outSum = sum;
    *outEvens = evens;
    *outOdds = odds;
}

int main(void) {
    int arr[100], n;
    printf("How many elements? ");
    if (scanf("%d", &n) != 1 || n <= 0) return 1;
    printf("Enter %d integers: ", n);
    for (int i = 0; i < n; i++) scanf("%d", &arr[i]);

    long long sum;
    int evens, odds;
    analyze(arr, n, &sum, &evens, &odds);

    printf("Sum: %lld\n", sum);
    printf("Even elements: %d\n", evens);
    printf("Odd elements: %d\n", odds);
    printf("Average: %.2f\n", (double)sum / n);

    return 0;
}
                                    

This shows the power of a single pass — one loop, three outputs. The analyze function takes three output pointers to return the three computed values. If you called three separate functions, you'd traverse the array three times. One loop with three accumulators is faster and, in this case, no less clear.

And a version using recursion, which is elegant but not efficient — included for completeness:

Variant: recursive sum

#include <stdio.h>

long long arraySumRec(const int arr[], int n) {
    if (n == 0) return 0;
    return arr[0] + arraySumRec(arr + 1, n - 1);
}

int main(void) {
    int arr[] = {1, 2, 3, 4, 5};
    printf("Sum: %lld\n", arraySumRec(arr, 5));
    return 0;
}
                                

The recursion says: "the sum of the array is the first element plus the sum of the rest." The base case (empty array) returns 0. Elegant — but for an array of 100,000 elements, you'd have 100,000 recursive calls, and stack overflow is likely. Iterative is the correct choice in practice. The recursive version is worth seeing once as a lesson in recursion, then setting aside.

Program Output

A typical run:

How many elements? 5
Enter 5 integers: 1 2 3 4 5
Sum: 15
Average: 3.00
                                

With negative numbers:

How many elements? 4
Enter 4 integers: 10 -5 3 -2
Sum: 6
Average: 1.50
                                

The sum is 10 + (-5) + 3 + (-2) = 6. Negative values subtract from the total, as expected. The average is 6 / 4 = 1.5. Both are correct.

With all zero values:

How many elements? 3
Enter 3 integers: 0 0 0
Sum: 0
Average: 0.00
                                

Zero is correctly handled — the sum of zeros is 0, and the average is 0.

With a single large value:

How many elements? 3
Enter 3 integers: 2000000000 2000000000 2000000000
Sum: 6000000000
Average: 2000000000.00
                                

Each value is 2 billion — just under INT_MAX. The sum is 6 billion, which exceeds INT_MAX and would overflow if we'd used int. Because we used long long, the sum is correct. This is why the return type matters.

And for the multi-output variant:

How many elements? 6
Enter 6 integers: 1 2 3 4 5 6
Sum: 21
Even elements: 3
Odd elements: 3
Average: 3.50
                                

Sum: 1 + 2 + 3 + 4 + 5 + 6 = 21. Evens: 2, 4, 6 (three). Odds: 1, 3, 5 (three). Average: 21 / 6 = 3.5. All correct in a single pass.

Step-by-Step Explanation

Let's trace the sum and look at the design choices.

1. Initialization: total = 0

Zero is the additive identity — adding it to any value returns the value. So starting with total = 0 means the first iteration computes 0 + arr[0] = arr[0], the second computes arr[0] + arr[1], and so on. At each point, total is "the sum of all elements seen so far."

For an empty array, the loop never runs, and total stays at 0. That's the correct sum of "nothing" — the empty sum is defined to be 0. This is why the sum function handles empty arrays naturally, unlike min and max (which have no valid "identity" for an empty set).

2. The loop

for (int i = 0; i < n; i++) total += arr[i]; — iterate over every element, adding each one to total. Unlike min/max, there's no comparison — every element contributes to the sum. This is why sum is simpler than min/max: no conditional logic, just accumulation.

3. Tracing arraySum({1, 2, 3, 4, 5}, 5)

  1. total = 0.
  2. i = 0: total += 1 → total = 1.
  3. i = 1: total += 2 → total = 3.
  4. i = 2: total += 3 → total = 6.
  5. i = 3: total += 4 → total = 10.
  6. i = 4: total += 5 → total = 15.
  7. Loop ends. Return 15. ✓

After each iteration, total holds the sum of the elements processed so far. The final value is the sum of all elements.

4. The long long return type

Each element is int — at most about 2.1 billion. But the sum of many elements can exceed that. Three INT_MAX values sum to about 6.4 billion, which overflows a 32-bit int. Using long long (typically 64-bit) allows the sum to grow to about 9.2 quintillion before overflowing, which is more than enough for any realistic array.

The promotion in total += arr[i] is automatic: total is long long, so the int value of arr[i] is converted to long long before the addition. There's no truncation of the individual element, and the sum accumulates in the wider type. This is exactly what we want.

5. Computing the average

(double)total / n — the cast to double is essential. Without it, total / n would be integer division: 15 / 5 would be 3 (correct), but 15 / 4 would be 3 instead of 3.75. The cast forces floating-point division, preserving the fractional part. This is one of the most common bugs in "average" code — if the numbers all divide evenly in your tests, you won't notice, but real data usually doesn't.

6. Empty array behavior

If n == 0, the loop doesn't execute, and the function returns 0. Is this correct? By convention, the sum of an empty array is 0 — the additive identity. So yes, the function handles it correctly without any special check. This is a nice property: sum has a natural identity, so empty sums make sense. Min and max don't have identities (there's no "empty max"), so they need special handling.

Note: our program rejects n <= 0 at input time, so this case doesn't arise in practice. But if you removed that check, the function would still return 0 for an empty array — a valid answer.

7. Multiple reductions in one pass

The analyze variant computes sum, evens, and odds all in a single loop. This is a common pattern in data analysis: one traversal, multiple accumulators. For large arrays, this is significantly faster than three separate functions, each traversing the array independently. The tradeoff is a slightly more complex function signature (multiple output pointers), but for a common "compute several stats" operation, it's the right structure.

8. Relation to other reductions

Sum is the simplest reduction, but the pattern generalizes:

  • Product: initialize to 1 (the multiplicative identity), multiply each element.
  • Count: initialize to 0, add 1 for each element matching a predicate.
  • Max: initialize to arr[0], replace on larger element.
  • Min: initialize to arr[0], replace on smaller element.
  • Any: initialize to false, return true on first match.
  • All: initialize to true, return false on first non-match.

All of these follow the same template: pick an identity, iterate, combine. The identity and the combine operation vary. That's the essence of a "reduction" or "fold" — the concept that unifies all these simple array traversals.

9. Complexity

O(n) time, O(1) extra space. One pass, one accumulator. Optimal for this problem — you have to touch every element to compute the sum, so you can't do better than O(n).

10. Extensions to statistics

Once you have the sum, several other statistics are one step away:

  • Mean: sum / n (with a cast to double).
  • Variance: sum of (x - mean)² / n. Requires two passes or one clever one-pass formula.
  • Standard deviation: sqrt of variance (needs <math.h>).
  • Weighted sum: sum of (weight × value). Same pattern with two arrays.
  • Prefix sums: an output array where each element is the sum of the input up to that point. Useful for answering range queries in O(1).

These are natural extensions of the sum. Each builds on the same linear scan, adding a small twist.

🔍 Try this: modify the program to also compute the product of all elements (initialize to 1, multiply each). Then compute the sum of squares (square each element before adding). Then compute the sum of only the even elements (check arr[i] % 2 == 0 before adding). Each is a small twist on the same loop — the identity and combine operation change, but the structure stays the same. That's the reduction pattern in action.

Frequently Asked Questions

1. Why long long instead of int for the return type?

Because sums grow quickly. Three INT_MAX values already overflow a 32-bit int. Using long long (typically 64-bit) gives you about 9.2 quintillion of headroom — more than enough for any realistic array. The cost is minimal (8 bytes vs 4 for the return value), and the benefit is avoiding silent overflow, which is one of the most insidious bug classes in C. For a general-purpose sum function, always prefer the wider type.

2. What's the sum of an empty array?

Zero. By convention, the empty sum is defined to be 0 — the additive identity. This is consistent with the rule that the sum of a set of values is the sum of all its elements, and the empty set has no elements to add. Our function correctly returns 0 when n == 0, because the loop doesn't execute and total stays at 0. This is a nice property of sum that min/max don't share — min and max of an empty set are undefined, which is why those functions need special handling.

3. How do I compute the average without losing precision?

Cast to double before dividing: (double)total / n. Without the cast, you'd get integer division, which truncates to the nearest whole number. For example, 15 / 4 in integer arithmetic is 3 (not 3.75). The cast forces floating-point division, preserving the fractional part. This is one of the most common bugs in average functions — if all your test data happens to divide evenly, you won't see it, but real data usually doesn't.

4. What's the difference between sum and prefix sum?

sum reduces an array to a single value — the total. prefix sum (or "cumulative sum") produces an array of the same length, where each element is the sum of all elements up to and including that index. For {1, 2, 3, 4, 5}, the sum is 15 and the prefix sum is {1, 3, 6, 10, 15}. Prefix sums are useful for answering "sum of elements from i to j" queries in O(1) time (via prefix[j] - prefix[i-1]). It's a natural extension of the sum, and a building block for many algorithmic techniques.

5. Can I use float or double for the array elements?

Yes — change the array parameter type to const double arr[], the accumulator to double total, and the return type to double. The loop logic stays the same. The caveat is that floating-point addition isn't perfectly associative — the order of additions can affect the final result due to rounding. For most applications this doesn't matter (the differences are tiny), but for high-precision numerical work, you might need techniques like Kahan summation to reduce rounding error. For typical "average a list of numbers" tasks, the naive sum is fine.

6. How can I sum elements that match a condition?

Add a conditional inside the loop: if (arr[i] % 2 == 0) total += arr[i]; — sums only even elements. Or if (arr[i] > 0) total += arr[i]; — sums only positive values. The pattern generalizes: "sum of elements matching predicate P" is just "for each element, if P(arr[i]), add it." This is a filtered reduction, and it's one of the most flexible patterns in programming. Once you see it, you'll find it everywhere — from "total of invoices over $100" to "sum of scores from winning games."

💡 Tip: Once this works, write arrayProduct(arr, n) — the multiplicative analog. Initialize to 1, multiply each element. Then arrayCountEven(arr, n) and arrayCountPositive(arr, n) — counts of elements matching a condition. Then arraySumPositive(arr, n) — sum of only positive elements. Each is a small, well-defined function that uses the same linear scan. Together they form a small library of array reductions that will handle a huge variety of problems.

📖 Related Tutorials

  • Introduction to Functions in C
  • One Dimensional Arrays
  • Passing Arrays to Functions
  • Function Definition
  • Function Declaration
  • Previous: Find the Minimum Element in an Array
  • Next: Search for an Element in an Array
  • All 33 Function Assignments

Previous Topic: -->> 19. Find the Minimum Element in an Array Using a Function   ||   Next Topic: -->> 21. Search for an Element in an Array Using a Function


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.