In: Computer Science
In C
Write a program to read a one-dimensional array, print sum of all elements using Dynamic Memory Allocation.
//If you have any doubts please comment me
//If you like my answer please up vote
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p,n,i,sum=0;
printf("Enter the size of Array Here\n");//Ask the
user to size of the array
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int));//this is for dynamic
memory
//now ask the values from the user
printf("Enter the array values below:\n");
for(i=0;i<n;i++)
{
printf("Enter number
%d:",i+1);
scanf("%d",(p+i));
}
//now sum calculation is here
for(i=0;i<n;i++)
{
sum=sum+*(p+i);
}
//Now we have to print the sum
printf("\nSum is:%d",sum);
//now we have to free the memory by using free
free(p);
}
Output: