Write a ‘C’ Program to compute the sum of all elements stored in an array using pointers

C ProgrammingProgramming

In C programming, arrays and pointers are powerful features that allow efficient manipulation of data. Utilizing pointers to access and traverse array elements can lead to more concise and sometimes more efficient code. In this article, we'll discuss how to compute the sum of all elements stored in an array using pointers in C, along with a practical example.

Example:

#include <stdio.h>

int arraySum(int *ptr, int size) {
    int sum = 0;
    int *end = ptr + size;  // Pointer to the end of the array

    for (; ptr < end; ptr++) {
        sum += *ptr;  // Dereferencing pointer to access array element
    }

    return sum;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);

    int sum = arraySum(arr, size);

    printf("Sum of array elements: %d\n", sum);

    return 0;
}

Explanation:

  1. The function `arraySum` takes two arguments: a pointer to the first element of the array (`ptr`) and the size of the array (`size`).
  2. Within `arraySum`, a variable `sum` is initialized to store the sum of array elements.
  3. Another pointer `end` is created, pointing to the end of the array by adding the size of the array to the base pointer `ptr`.
  4. A `for` loop iterates through each element of the array using pointer arithmetic until `ptr` reaches `end`.
  5. Inside the loop, each element is accessed using the dereferencing operator `*`, and its value is added to the `sum`.
  6. Once all elements are traversed, the `sum` is returned.
  7. In the `main` function, an array `arr` is initialized with some values, and its size is calculated using `sizeof` operator.
  8. The `arraySum` function is called with the array `arr` and its size as arguments, and the result is stored in the variable `sum`.
  9. Finally, the sum is printed to the console using `printf`.

Conclusion:

Using pointers to access array elements in C provides a more efficient way to manipulate data. By understanding the relationship between arrays and pointers, programmers can write cleaner and more concise code. The example provided demonstrates how to compute the sum of array elements using pointers, showcasing the power and versatility of these concepts in C programming.

       

Advertisements

ads