C Program to Calculate the Sum of the Array Elements using Pointer


  1. #include <stdio.h>
  2. #include <malloc.h>
  3. 
    
  4. void main()
  5. {
  6.     int i, n, sum = 0;
  7.     int *a;
  8. 
    
  9.     printf("Enter the size of array A \n");
  10.     scanf("%d", &n);
  11.     a = (int *) malloc(n * sizeof(int));
  12.     printf("Enter Elements of First List \n");
  13.     for (i = 0; i < n; i++)
  14.     {
  15.         scanf("%d", a + i);
  16.     }
  17.     </*  Compute the sum of all elements in the given array */
  18.     for (i = 0; i < n; i++)
  19.     {
  20.         sum = sum + *(a + i);
  21.     }
  22.     printf("Sum of all elements in array = %d\n", sum);
  23. }

 

output:

Enter the size of array A
5
Enter Elements of First List
4
9
10
56
100
Sum of all elements in array = 179