C PROGRAMMING PROGRAM • POINTERS & DYNAMIC MEMORY
Find Array Sum Using Pointer Arithmetic
Learn how to find array sum using pointer arithmetic using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
5 10 20 30 40 50
Sample output
Sum = 150
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int size, values[100];
long long sum = 0;
scanf("%d", &size);
if (size < 1 || size > 100) return 1;
for (int index = 0; index < size; index++) scanf("%d", values + index);
for (int *current = values; current < values + size; current++) sum += *current;
printf("Sum = %lld\n", sum);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Sum = 150
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Move a pointer through the array and add each dereferenced value.
- Display the computed result.
Move a pointer through the array and add each dereferenced value.
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.
