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.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
5 3 6 9 12 15
Sample output
Sum = 45
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Sum = 45
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Allocate exactly N integers, use the memory like an array and release it with free().
- 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.
