Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using calloc( ) function. Understand the difference between the above two programs

Previous
Next

Solution:

Like malloc, calloc also allocates memory at runtime and is defined in stdlib.h. It takes the number of elements and the size of each element(in bytes), initializes each element to zero and then returns a void pointer to the memory.

Its syntax is

void *calloc(n, element-size);

Here, ‘n’ is the number of elements and ‘element-size’ is the size of each element.

#include <stdlib.h>
int main()
{
	int n, i, *p, sum=0;
	printf("Enter number of elements: ");
	scanf("%d",&n);
	p=(int*)calloc(n, sizeof(int));  
	if(p == NULL)
	{
		printf("memory cannot be allocated\n");
	}
	else
	{
		printf("Enter elements of array:\n");
		for(i=0;i<n;++i)
		{
			scanf("%d",p+i);
		}
		
		for(i=0;i<n;i++)
		{
			sum = sum + (*(p+i));
		}
		printf("Elements sum is : %d \n", sum);
	}
	return 0;
}
Previous
Next

Courses Enquiry Form