Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using malloc() function.

Previous
Next

Solution:

  • In this program, we used malloc() function to allocate the memory.
  • After memory allocation, we read the elements into array using for loop with expression “p+i”.
  • Using pointer variable “p” and it’s increment, we find the sum of all elements in the array.
#include<stdio.h>
#include<stdlib.h>
main()
{
	int *p, i, n, sum=0;
	printf("\nEnter the elements size: ");
	scanf("%d", &n);
	p=(int *)malloc(n*sizeof(int));
	printf("\nEnter the array values: \n");
	for(i=0;i<n;i++)
	{
		scanf("%d",p+i);
	}
	for(i=0; i<n; i++)
	{
		sum = sum + *p;
		p++;
	}
	printf("\nThe sum of elements is: %d\n", sum);
}
Previous
Next

Courses Enquiry Form