PPS Lab · Experiment 27
Sum of n array elements using a pointer
CArrays, pointers and functionsJNTUH R22 · CS108ES
Aim
To write a C program that reads n integers into an array and finds the sum of the elements by accessing them through a pointer variable.
Algorithm
- Read n. If it is not between 1 and 50, print an error and stop.
- Read the n integers into the array a.
- Set the pointer p to the first element (p = a) and sum to 0.
- For i from 0 to n − 1, add the value at p + i, that is *(p + i), to sum.
- Print the sum.
Program
#include <stdio.h>
#define MAX 50
int main(void) {
int a[MAX], n;
int *p = a; /* p points to a[0] */
int sum = 0;
printf("Enter the number of elements (1 to %d): ", MAX);
if (scanf("%d", &n) != 1 || n < 1 || n > MAX) {
printf("Invalid number of elements\n");
return 1;
}
printf("Enter %d integers: ", n);
for (int i = 0; i < n; i++) {
if (scanf("%d", &a[i]) != 1) {
printf("Invalid input\n");
return 1;
}
}
for (int i = 0; i < n; i++) {
sum += *(p + i); /* value of a[i], read through the pointer */
}
printf("Sum of the %d elements = %d\n", n, sum);
return 0;
}Output
Six elements
Enter the number of elements (1 to 50): 6
Enter 6 integers: 5 10 15 20 25 30
Sum of the 6 elements = 105With negative numbers
Enter the number of elements (1 to 50): 4
Enter 4 integers: 100 -45 7 -2
Sum of the 4 elements = 60Recorded by compiling and running this exact program. Typed input appears after each prompt.
How it works
*(p + i) is the value of a[i]: p + i is the address i elements after a[0], and * reads the value at that address.
The same loop can be written by moving the pointer itself: for (p = a; p < a + n; p++) sum += *p;. Both are correct.
Common mistakes
Writing
sum += p + i;without the*. That adds an address, not a value, and the compiler reports an error or warning.Writing
*p + iinstead of*(p + i).*is applied first, so*p + iisa[0] + i, nota[i].Not setting
sum = 0before the loop. A local variable starts with a garbage value, so the total is wrong.Moving the pointer with
p++in the loop and then usingpagain later as if it still pointed toa[0]. Reset it withp = afirst.
Viva questions
Try to answer each one aloud before you open it.
What is the difference between *(p + i) and *p + i?
*(p + i)is the value of the element i places after the one p points to.*p + iis the value p points to, plus i, because*is applied before+.If int takes 4 bytes and p holds address 1000, what is p + 3?
- Adding 3 to an
intpointer moves it 3 × 4 = 12 bytes.
- Adding 3 to an
Which one is the same as a[i]: *(a + i) or *a + i?
*(a + i). The compiler actually turnsa[i]into*(a + i).What is a NULL pointer?
A pointer that points to nothing, holding the value
NULL. Dereferencing it is an error, so pointers should be checked before use when they might be NULL.Why use a pointer to access an array at all?
Pointers let functions work on arrays without copying them, and moving a pointer through memory is the basis of strings, dynamic memory and many library functions.