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

0
#include <stdio.h>
 
#include <stdlib.h>
 
int main()
 
{
 
int *ptr,sum=0,n,i;
 
int a[10];
 
ptr=a;
 
printf(“enter the number of elements\n”);
 
scanf(“%d”,&n);
 
printf(“enter the array elements\n”);
 
for(i=0;i<n;i++)
 
scanf(“%d”,&a[i]);
 
printf(“MEMORY LOCATION OF THE FIRST VALUE %u\n”,&ptr[0]);
 
i=0;
 
while(i<n)
 
{
 
sum=sum+(*ptr);
 
i++;
 
ptr++;
 
}
 
printf(“sum is %d\n”,sum);
 
printf(“FINAL MEMORY LOCATION AFTER ACCESSING %d INTEGERS IS ptr=%u”,n,ptr);
 
return 0;
 
}
enter the number of elements
5
enter the array elements
1
2
3
4
5
MEMORY LOCATION OF THE FIRST VALUE 2752216
sum is 15
FINAL MEMORY LOCATION AFTER ACCESSING IN 5 INTEGERS ptr=2752236
#include <stdio.h>
 
#include <malloc.h>
 
void main()
 
{
    int i, n, sum = 0;
 
    int *a;
 
        printf("Enter the size of array A \n");
 
    scanf("%d", &n);
 
        a = (int *) malloc(n * sizeof(int));
 
        printf("Enter Elements of First List \n");
 
    for (i = 0; i < n; i++) 
 
        {
 
        scanf("%d", a + i);
 
    }
 
        for (i = 0; i < n; i++)
 
        {
 
        sum = sum + *(a + i);
 
    }
 
        printf("Sum of all elements in array = %d\n", sum)
}
Enter the size of array A
5
Enter Elements of First List
4
9
10
56
100
Sum of all elements in array = 179

Leave a Reply

Your email address will not be published. Required fields are marked *