Find Sum of Array in C

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Arrays

What You’ll Learn

Summing an array means visiting every element once and adding it to a running total (the accumulator pattern). Example: {1, 2, 3, 4, 5} → 15. Empty arrays sum to 0; negatives are allowed. This tutorial covers a manual loop, user input, a live preview, worked C examples, edge cases, and complexity.

Start at 0

Accumulator

Zero is the additive identity.

One Pass

total += x

Visit each element exactly once.

Empty = 0

Edge case

No elements means the total stays 0.

Negatives OK

Same loop

They simply reduce the total.

Live Preview

Try 1,2,3,4,5

Compute a custom array instantly.

Loop vs long long

Interview tip

Show the loop; prefer long long for the total.

Introduction

Summing an array is the simplest one-pass array problem: keep a running total and add every value. With [1, 2, 3, 4, 5] the total climbs 0 → 1 → 3 → 6 → 10 → 15.

Interviews want the manual accumulator so you prove you understand traversal. Prefer long long for the running total so large arrays are less likely to overflow int.

Why it matters?

It is the foundation for averages, prefix sums, and many later array scans (max, min, product).

Key Highlights

Accumulator

total starts at 0.

Single Pass

O(n) time, O(1) space.

Empty = 0

Natural with this pattern.

Next: Max

Same scan, different keep.

In short: total = 0, then total += value for every element.

📝 Problem & Approach

Given an array of integers, return the sum of all elements.

c
/* {1, 2, 3, 4, 5} -> 15
   {10, -2, 7}     -> 15
   {} (n = 0)      -> 0 */

Inputs & Outputs

ItemTypeDescription
arrint[] + sizeValues to add (may be empty).
ReturnintSum of all elements (0 if empty).
totalintRunning accumulator.

Minimal workflow

Pseudocode
function array_sum(arr):
    total = 0
    for (i = 0; i < n; ++i):
        total += value
    return total

Method comparison

MethodIdeaNotes
Manual looptotal += valueInterview default
Wider sum typelong long sumSafer for large totals
Index loopfor (i = 0; i < n; ++i)Same O(n); useful with indices

⚡ Quick Reference

GoalPattern
Inittotal = 0
Addtotal += value
For-eachfor (i = 0; i < size; ++i)
By indexfor (i = 0; i < n; ++i) total += arr[i];
Safer totallong long sum
Emptyn = 00

📋 Loop vs long long vs Index

Same result — different packaging.

Accumulator
total += x

Clearest interview answer

long long
long long

Safer running total type

Index
arr[i]

When you also need positions

vs max
keep best

Same pass, different update

Context

When This Problem Shows Up

Reach for an array sum whenever you need a one-pass total.

  1. Interview warm-ups

    First array traversal after variables.

  2. Averages

    Sum then divide by length.

  3. Prefix sums

    Running totals unlock range queries.

  4. Input parsing

    Read n values, then total them.

  5. Not for products

    Product starts at 1, not 0.

Key benefit: one pattern — start at 0, add everything — that transfers to almost every array scan.

🔮 Live Preview

Enter integers separated by commas or spaces and compute the sum instantly.

Integers only (safe integer range), up to 2000 values. Empty input sums to 0.

Live result
Press “Compute sum”.

Examples Gallery

Three complete C programs — sum a fixed array, read user input, and show a running total with negatives. Click View Output to reveal sample console results.

📚 Getting Started

The classic accumulator on a hard-coded array.

Example 1 — Sum of a Fixed Array

Classic example: {1, 2, 3, 4, 5} → 15.

c
#include <stdio.h>

long long sum_array(const int arr[], int size) {
    long long sum = 0;
    int i;

    for (i = 0; i < size; ++i) {
        sum += arr[i];
    }

    return sum;
}

int main(void) {
    int array[] = { 1, 2, 3, 4, 5 };
    int size = (int)(sizeof array / sizeof array[0]);
    long long sum = sum_array(array, size);

    printf("Sum of the array elements: %lld\n", sum);
    return 0;
}

How It Works

total starts at 0 and climbs as each value is added: 1, then 3, 6, 10, and finally 15.

⚡ Reading Input

Same helper, values come from the user.

Example 2 — Sum of an Array (User Input)

Reads n and then n numbers from the user. Rejects a negative length.

c
#include <stdio.h>

int main(void) {
    int n;
    int i;

    printf("Enter number of elements: ");
    if (scanf("%d", &n) != 1 || n < 0) {
        printf("Invalid n.\n");
        return 0;
    }

    long long sum = 0;

    for (i = 0; i < n; ++i) {
        long long x;

        printf("Enter element %d: ", i + 1);
        if (scanf("%lld", &x) != 1) {
            printf("Invalid input.\n");
            return 0;
        }

        sum += x;
    }

    printf("Sum of the array elements: %lld\n", sum);
    return 0;
}

How It Works

Read n and each element with scanf, adding into a long long as you go. Checking scanf return values avoids using uninitialized input.

Example 3 — Running Total with Negatives

Print the accumulator after each step so you can see negatives reduce the total.

c
#include <stdio.h>

int main(void) {
    int arr[] = { 10, -2, 7 };
    int size = (int)(sizeof arr / sizeof arr[0]);
    long long total = 0;
    int i;

    printf("Running total:\n");

    for (i = 0; i < size; ++i) {
        total += arr[i];
        printf("  after %+d: %lld\n", arr[i], total);
    }

    printf("Final sum: %lld\n", total);
    return 0;
}

How It Works

Negatives are not special-cased — addition handles them. Tracing the running total is a great whiteboard habit.

🧠 How the Algorithm Adds

1

Set total = 0

Additive identity for an empty start.

Init
2

Visit each value

for (i = 0; i < n; ++i)

Loop
3

total += value

Fold the next element into the sum.

Update
=

Return total

After the loop, total is the answer.

🔎 Worked Walkthrough — [1, 2, 3, 4, 5]

Watch the accumulator climb from 0 to 15.

Stepvaluetotal after
start0
111
223
336
4410
5515

Same table works for [10, -2, 7]: 0 → 10 → 8 → 15.

Use Cases

Where array sums show up beyond the interview prompt.

1. Interview Basics

First array traversal drill.

Example: sum_array([1,2,3]).

2. Averages

Sum then divide by n.

Example: average tutorials.

3. Totals in Apps

Cart totals, scores, balances.

Example: add line items.

4. Prefix Sums

Store running totals for ranges.

Example: range queries.

5. Validation

Checksum-style quick totals.

Example: live preview.

6. Next: Maximum

Same pass, keep the best.

Example: related CTA.

Pro Tip: say “accumulator starts at zero” before you write the loop.

Advantages

Why the one-pass accumulator is the right first approach.

  1. 1. Simple to Explain

    One variable, one loop, one update.

  2. 2. Optimal for Unsorted Lists

    You must look at every element anyway.

  3. 3. Tiny Extra Memory

    Only the accumulator — O(1) space.

  4. 4. Handles Edges Naturally

    Empty arrays and negatives need no special cases.

Pro Tip: mention long long as a safer total after you show the manual loop.

Usage Tips

Small habits that keep sum solutions interview-ready.

  1. 1. Start at Zero

    Never seed with arr[0] for summing.

  2. 2. One Loop Only

    Do not nest or sort first.

  3. 3. Validate Input

    Guard negative n when reading length.

  4. 4. Trace on Paper

    Write the running total for small arrays.

  5. 5. Know long long

    Mention it after the manual solution.

Pro Tip: sanity-check [], [1,2,3,4,5], and [10,-2,7] — if those three work, you are solid.

Common Pitfalls

Mistakes that commonly break sum-of-array programs.

  1. 1. Starting total at arr[0]

    That pattern is for max/min, not sum.

    → Always start sum at 0.

  2. 2. Skipping Empty Lists

    Crashing when n = 0.

    → Empty sum is 0 with this pattern.

  3. 3. Rejecting Negatives

    Treating them as invalid.

    → Addition already handles them.

  4. 4. Sorting First

    Unnecessary O(n log n) work.

    → One linear pass is enough.

  5. 5. Mixing Strings

    Unvalidated input breaks int conversion.

    → Validate before summing.

Edge Cases

Handle these before claiming the sum is complete.

Empty array

Sum = 0

Result remains 0.

Negatives

Valid input

They reduce the total naturally.

Single element

Sum = that value

[7] → 7.

Invalid input

Validate safely

Handle non-numeric values before summing.

n < 0

Reject length

Raise or re-prompt.

Zeros

No change

Adding 0 leaves total unchanged.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Additive identity. Starting at 0 is what makes empty arrays (n = 0) work.
  • Must see every element. You cannot skip values in an unsorted array.
  • Order does not matter. Integer addition is commutative.
  • Product is different. Products start at 1, not 0.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Sum [1..5]

  • Reproduce Example 1
  • Expect 15

2. Trace [10,-2,7]

  • Show running totals
  • Match Example 3

3. Empty array

  • Confirm sum = 0
  • No special branch needed

4. Average follow-up

  • Sum then / len(arr)
  • Guard empty length

Notes

  • Pattern: accumulator starts at 0, then add each element once.
  • Complexity: O(n) time and O(1) extra space.
  • Safety: use long long for the total after you can write the loop.
  • Next skill: keep a running maximum or minimum with the same one-pass shape.

Quick Takeaway: total = 0; for each value, total += value.

⏱️ Time and Space Complexity

ApproachTimeExtra space
Single passO(n)O(1)
long long totalO(n)O(1)
Sort then addO(n log n)varies

You must read every element, so linear time is optimal for an unsorted array.

Wrap Up

🎉 Conclusion

Summing an array is the accumulator pattern: start at 0, add every element once, return the total. Empty arrays stay 0; negatives just subtract.

Practice the three examples above, then continue to finding the maximum of an array.

total = 0; total += each value.

💡 Best Practices

✅ Do

  • Start total at 0
  • Visit every element once
  • Allow negatives
  • Treat empty as 0
  • Mention long long after the loop

❌ Don’t

  • Seed total with arr[0]
  • Sort just to sum
  • Forget empty arrays sum to 0
  • Skip input validation
  • Confuse with product (starts at 1)

Key Takeaways

Knowledge Unlocked

Five things to remember about summing arrays

Master the accumulator pattern for every later scan.

5
Core concepts
+ 02

Add

total += x

Loop
[] 03

Empty

sum is 0

Edge
- 04

Negatives

just subtract

Input
O 05

Cost

O(n) / O(1)

Analysis

❓ Frequently Asked Questions

Initialize sum to 0, then loop through the array and add each element: sum += arr[i]. Print sum at the end.
Because 0 is the identity for addition. If you start from 0 and add every element once, you get exactly the total.
Yes. The same loop works; negative numbers reduce the total.
Use long long if the array may contain big values or many items. It reduces overflow risk compared to int.
O(n) time and O(1) extra space.
By the accumulator pattern, the answer is 0.
No. Addition is associative and commutative for ordinary integers.
Say accumulator out loud, start at 0, walk every element once, and mention long long for safer totals.

Did you Know? 🔊

The “sum of an array” program is the simplest example of the accumulator pattern: start with sum = 0, then add each element once. This idea appears everywhere: totals, averages, dot products, and prefix sums.

Continue to Maximum of an Array

Learn how to find the largest element with a single linear scan.

Maximum of an array tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful