C PROGRAMMING PROGRAM • ARRAYS, SEARCHING & SORTING

Calculate Array Sum and Average

Learn how to calculate array sum and average using a clear C program.

BeginnerArraysLoopsIndexing

PROBLEM UNDERSTANDING

Input and expected output

Sample input
5
10 20 30 40 50
Sample output
Sum = 150
Average = 30.00

COMPLETE C PROGRAM

Complete C implementation

array-sum-and-average.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int size, values[100];
    long long sum = 0;

    printf("Enter array size: ");
    scanf("%d", &size);
    if (size < 1 || size > 100) return 1;
    printf("Enter %d integers: ", size);
    for (int index = 0; index < size; index++) {
        scanf("%d", &values[index]);
        sum += values[index];
    }
    printf("Sum = %lld\nAverage = %.2f\n", sum, (double) sum / size);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Sum = 150
Average = 30.00
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Accumulate values while reading, then divide the sum by the number of elements.
  3. Display the computed result.

Accumulate values while reading, then divide the sum by the number of elements.

EFFICIENCY

Time and space complexity

Time complexity

O(n)

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.