Write a c program to find sum and average of array elements using a pointer with an example. In this c example, we assigned the array to the pointer variable and used the pointer to read and find the sum and average of array elements using a for loop.
#include <stdio.h> int main() { int Size, i, sum = 0; printf("Please Enter the Array size = "); scanf("%d", &Size); int arr[Size]; int *parr = arr; printf("Enter the Array Items = "); for (i = 0; i < Size; i++) { scanf("%d", parr + i); } for (i = 0; i < Size; i++) { sum = sum + *(parr + i); } float avg = (float)sum / Size; printf("\nThe Sum of Array Items = %d\n", sum); printf("\nThe Average of Array Items = %.2f\n", avg); }
Please Enter the Array size = 9
Enter the Array Items = 21 31 41 51 61 71 81 91 121
The Sum of Array Items = 569
The Average of Array Items = 63.22
In this c program, we removed extra for loop and calculated the sum and average of array elements using pointer.
#include <stdio.h> int main() { int Size, sum = 0; printf("Please Enter the Array size = "); scanf("%d", &Size); int arr[Size]; int *parr = arr; printf("Enter the Array Items = "); for (int i = 0; i < Size; i++) { scanf("%d", parr + i); sum = sum + *(parr + i); } float avg = (float)sum / Size; printf("\nThe Sum of Array Items = %d\n", sum); printf("\nThe Average of Array Items = %.2f\n", avg); }