Write a program to find the sum of all array elements using dynamic memory allocation
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,sum=0,*a;
clrscr();
printf("How many elements? ");
scanf("%d",&n);
a=(int *)malloc(n*sizeof(int));
printf("Enter the elements:\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",sum);
getch();
}
Output:
How many elements? 5
Enter the elements:
1
2
3
4
5
Sum of all elements in array=15
No comments: