1. Introduction
Pointers in C provide a powerful tool for accessing and manipulating data in memory. They can be used to navigate and manipulate various data structures, including arrays. In this post, we will look into a C program that computes the sum of array elements using pointers.
2. Program Overview
1. Declare an array of integers.
2. Use a pointer to traverse through the array.
3. Accumulate the sum of all elements using the pointer.
4. Display the computed sum.
3. Code Program
#include <stdio.h>
int main() {
int arr[5]; // Declare an array of integers
int *ptr; // Declare an integer pointer
int sum = 0; // Initialize sum
int i;
// Input array elements
printf("Enter 5 elements of the array: ");
for(i = 0; i < 5; i++) {
scanf("%d", &arr[i]);
}
// Use the pointer to traverse and compute the sum
ptr = arr; // Point to the first element of the array
for(i = 0; i < 5; i++) {
sum += *ptr; // Add the value pointed by ptr to sum
ptr++; // Move the pointer to the next array element
}
// Display the result
printf("Sum of array elements: %d\n", sum);
return 0;
}
Output:
Enter 5 elements of the array: 1 2 3 4 5 Sum of array elements: 15
4. Step By Step Explanation
1. The program begins by declaring an array arr of 5 integers and a pointer ptr that will be used to navigate the array.
2. The user is prompted to input 5 integers, which are stored in the array.
3. The pointer ptr is then made to point to the first element of the array with the statement ptr = arr;.
4. A for loop is used to traverse the array. Within the loop, the value pointed by ptr (which is an element of the array) is added to the sum variable.
5. The pointer ptr is then incremented using ptr++ to move to the next array element.
6. This process is repeated until all elements of the array have been summed up.
7. The final result, the sum of all array elements, is then printed out.
Comments
Post a Comment
Leave Comment