Placement Prep

Sum of Array Elements: C, C++, Java, and Python

Find the sum of elements in a given array using loop-based programs and built-in functions in C, C++, Java, and Python, with examples and complexity analysis.

By FACE Prep Team 5 min read
arrays array-sum c-program java-program python-program data-structures placement-prep

Given an array of integers, finding their sum needs one pass through the array and a running total: three lines of code in C, one function call in Python.

The Array Sum Problem

The task is direct: accept n integers, compute their total, and return the result.

  • Input: the number of elements n, then n integers
  • Output: a single integer equal to their sum

Sample inputs and expected outputs:

  • Input [1, 2, 3] → Output 6
  • Input [10, 20, 30, 40] → Output 100
  • Input [-5, 3, 7] → Output 5
  • Input [] (empty) → Output 0

The empty-array case and the negative-integer case are worth testing explicitly in interviews. Both are handled correctly by the standard loop when the accumulator starts at 0.

A related traversal pattern, summing the digits of a single number rather than the elements of an array, is covered in the sum of digits of a number guide.

Step-by-Step Algorithm

  • Step 1: Read n, the number of elements.
  • Step 2: Read the n elements into an array.
  • Step 3: Initialise sum = 0.
  • Step 4: For each element x in the array, add x to sum.
  • Step 5: Output sum.

No sorting, no extra data structures. The total traversal cost is one full pass through the array.

Programs in C and C++

C: Loop-Based

#include <stdio.h>

int main() {
    int n;
    printf("Enter number of elements: ");
    scanf("%d", &n);

    int arr[n];
    printf("Enter %d elements:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

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

    printf("Sum = %d\n", sum);
    return 0;
}
Sample run:
Input:  3   1   2   3
Output: Sum = 6

The inner loop visits arr[0] through arr[n-1] in order, adding each value to sum. The accumulator starts at 0, so negative elements subtract correctly and an empty array produces 0.

C++: Loop and std::accumulate

C++ supports the same manual loop via a range-based for. It also ships std::accumulate in the <numeric> header, which takes begin and end iterators plus an initial value and collapses the loop to a single expression.

#include <iostream>
#include <numeric>
#include <vector>
using namespace std;

int main() {
    int n;
    cout << "Enter number of elements: ";
    cin >> n;

    vector<int> arr(n);
    cout << "Enter " << n << " elements:\n";
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }

    // Loop-based
    int sum = 0;
    for (int x : arr) {
        sum += x;
    }
    cout << "Sum (loop) = " << sum << "\n";

    // std::accumulate
    int accSum = accumulate(arr.begin(), arr.end(), 0);
    cout << "Sum (accumulate) = " << accSum << "\n";

    return 0;
}
Sample run:
Input:  4   10   20   30   40
Output: Sum (loop) = 100
        Sum (accumulate) = 100

Both give identical results. std::accumulate is preferred in production code for clarity; the explicit loop is better in interviews when the examiner wants to see traversal logic.

Programs in Java and Python

Java: Loop and Arrays.stream().sum()

import java.util.Arrays;
import java.util.Scanner;

public class ArraySum {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number of elements: ");
        int n = sc.nextInt();

        int[] arr = new int[n];
        System.out.println("Enter " + n + " elements:");
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        // Loop-based
        int sum = 0;
        for (int x : arr) {
            sum += x;
        }
        System.out.println("Sum (loop) = " + sum);

        // Stream-based
        int streamSum = Arrays.stream(arr).sum();
        System.out.println("Sum (stream) = " + streamSum);
    }
}
Sample run:
Input:  3   1   2   3
Output: Sum (loop) = 6
        Sum (stream) = 6

Arrays.stream(int[]) returns an IntStream, and IntStream.sum() returns int. The loop and stream results are always identical for the same input.

Python: Loop and sum()

Python’s built-in sum() accepts any iterable, so the one-liner is completely idiomatic for production code.

n = int(input("Enter number of elements: "))
arr = []
for _ in range(n):
    arr.append(int(input()))

# Loop-based
total = 0
for x in arr:
    total += x
print("Sum (loop) =", total)

# Built-in
print("Sum (built-in) =", sum(arr))
Sample run:
Input:  3   1   2   3
Output: Sum (loop) = 6
        Sum (built-in) = 6

For a one-liner input: arr = list(map(int, input().split())) then print(sum(arr)). Most placement coding platforms accept either style.

Complexity Analysis

ApproachLanguageTimeSpace
Manual loopC, C++, Java, PythonO(n)O(1)
std::accumulateC++O(n)O(1)
Arrays.stream().sum()JavaO(n)O(1)
sum()PythonO(n)O(1)

All four approaches visit each element exactly once. None of them allocate data structures that grow with n, so the space cost stays at O(1) regardless of array size.

One practical concern: if n is large and element values are large, the running total can overflow a 32-bit integer. In C and Java, switch the accumulator to long when the input range is not guaranteed to fit in int. Python integers are arbitrary-precision, so overflow is not a concern there.

For a fuller explanation of how space complexity is measured across sorting, recursion, and hashing patterns, see space complexity of algorithms with examples.

Array Sums in Placement Interviews

Array sum rarely appears as a standalone hard problem in final placement rounds. It shows up in two ways:

  • Warm-up or opening question: TCS NQT, Cognizant GenC, and Capgemini coding sections typically begin with a direct array problem. Sum or average of elements is a standard choice for that opening slot.
  • Embedded subproblem: harder questions, such as finding the equilibrium index of an array, rely on prefix-sum logic built on the same traversal pattern.

Edge cases interviewers test:

  • An array with a single element: sum equals that element.
  • An array with all identical values: sum equals the value multiplied by the count.
  • An array containing both positive and negative integers: the loop handles this without a special case.
  • An empty array: sum is 0 when the accumulator is initialised to 0.

Getting all four of these correct in under two minutes, without compilation errors or off-by-one bugs, is what separates clean submissions from near-misses. The algorithm itself is not the differentiator; correct edge-case handling is.

Choose the explicit loop when an interviewer asks you to demonstrate traversal logic or when the interviewer’s platform shows your code step-by-step. Reach for sum(), accumulate(), or stream() when the problem just needs the total and readability is the goal.

The programs above cover both paths. The loop makes the O(n) traversal visible; sum() and std::accumulate wrap that same cost in a cleaner interface. Knowing which to reach for, and when, is the same judgment call that comes up in LLM-assisted coding. TinkerLLM lets you test that judgment at ₹299, letting you work with real AI APIs before placement season tightens the schedule.

Primary sources

Frequently asked questions

What is the time complexity of finding the sum of array elements?

O(n): the loop visits each element exactly once, and no auxiliary data structure grows with input size.

Can I use a built-in function instead of writing a loop?

Yes. Python's sum(), C++ std::accumulate, and Java's Arrays.stream().sum() each work in one line. Use the loop form when an interviewer asks you to show the traversal logic explicitly.

What if the array contains negative numbers?

Initialising the total to 0 means negative values subtract themselves from the running total automatically. No special case is needed.

What happens when the array is empty?

An empty array returns 0 when the total is initialised to 0 before the loop. That is mathematically correct: the sum of zero elements equals the additive identity.

Is array sum asked in placement coding tests?

Array manipulation including sum, prefix sums, and running totals appears in TCS NQT, Cognizant GenC, and Capgemini placement tests, usually as a warm-up or embedded inside a harder problem.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF