C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Sum of array using pointers

C Program: Sum of array using pointers

C

#include <stdio.h>

 

int main() {

    int n, i, sum = 0;

    int arr[100];

    int *ptr;

 

    // Input size of array

    printf("Enter number of elements: ");

    scanf("%d", &n);

 

    // Input array elements

    printf("Enter %d elements: ", n);

    for (i = 0; i < n; i++) {

        scanf("%d", &arr[i]);

    }

 

    // Pointer to first element of array

    ptr = arr;

 

    // Calculate sum using pointer

    for (i = 0; i < n; i++) {

        sum += *(ptr + i);

    }

 

    // Display result

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

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter number of elements: 5
Enter 5 elements: 10 20 30 40 50
Sum of array elements = 150

Explanation

  • The array arr holds the elements entered by the user.
  • The pointer ptr points to the first element of the array.
  • Using pointer arithmetic *(ptr + i), each element is accessed and added to sum.
  • Finally, the total sum is displayed.