C PROGRAMMING PROGRAM • POINTERS & DYNAMIC MEMORY

Create a Dynamic Array and Find Its Sum

Learn how to create a dynamic array and find its sum using a clear C program.

Intermediatemalloc()free()Dynamic array

PROBLEM UNDERSTANDING

Input and expected output

Sample input
5
3 6 9 12 15
Sample output
Sum = 45

COMPLETE C PROGRAM

Complete C implementation

dynamic-array-sum.c
Open in compiler
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int size;

    printf("Enter array size: ");
    scanf("%d", &size);
    if (size < 1 || size > 100000) return 1;
    int *values = malloc((size_t) size * sizeof *values);
    if (values == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }
    long long sum = 0;
    for (int index = 0; index < size; index++) {
        scanf("%d", &values[index]);
        sum += values[index];
    }
    printf("Sum = %lld\n", sum);
    free(values);
    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 = 45
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Allocate exactly N integers, use the memory like an array and release it with free().
  3. Display the computed result.

Allocate exactly N integers, use the memory like an array and release it with free().

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.