This C program demonstrates how to calculate the sum of all elements in an array using pointers. The program defines a function called `sum_of_array_elements` that takes an array and its size as arguments, then uses a pointer to traverse the array and compute the sum.
Code Implementation
#include <stdio.h>
// Function to calculate the sum of array elements using pointers
int sum_of_array_elements(int arr[], int size) {
int sum = 0;
int *ptr = arr; // Initialize pointer to the first element of the array
// Traverse the array using the pointer and calculate the sum
for (int i = 0; i < size; i++) {
sum += *ptr; // Dereference the pointer to access the current element
ptr++; // Increment the pointer to point to the next element
}
return sum;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Array elements: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
int sum = sum_of_array_elements(arr, size);
printf("Sum of array elements: %d\n", sum);
return 0;
}
Explanation
The `sum_of_array_elements` function takes an array `arr` and its size `size` as arguments. It initializes a pointer `ptr` to the first element of the array using `int *ptr = arr;`. Then, it uses a `for` loop to traverse the array, dereferencing the pointer to access each element and adding it to the sum. The pointer is incremented using `ptr++` to point to the next element in each iteration.
In the `main` function, we define an example array `arr` and calculate its size using `sizeof(arr) / sizeof(arr[0])`. We then call the `sum_of_array_elements` function, passing the array and its size as arguments, and print the result.
Output
When you run this program, it will output the sum of the array elements:
Array elements: 1 2 3 4 5
Sum of array elements: 15
Comments
Post a Comment