Summary: This program calculates the sum of all elements in an array using pointer arithmetic instead of array indexing. It demonstrates pointer traversal over an array using ptr++.
#include <stdio.h>
int main() {
int arr[100], n, sum = 0;
int *ptr;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
ptr = arr; // pointer points to first element
for (int i = 0; i < n; i++) {
sum += *(ptr + i); // pointer arithmetic
}
printf("Sum = %d\n", sum);
return 0;
}
Pointer Traversal:
The pointer ptr is initialized to point to the beginning of the array. Then, *(ptr + i) is used to access each element.
Why Pointer Arithmetic:
Instead of traditional arr[i] indexing, pointer arithmetic gives a deeper understanding of how arrays are laid out in memory.
Memory Efficiency:
This approach doesn't copy or shift any data. It operates directly on memory addresses, making it efficient.
User Interaction:
The user inputs the size and elements of the array, keeping the program interactive and testable with different input sizes.