C Program to calculate sum of all elements of array using calloc function
Objective
Write a C program to calculate the sum of array elements using the calloc function.
Algorithm / Approach
- Read
nelements. - Allocate memory using
ptr = (int*) calloc(n, sizeof(int)). - Check if allocation succeeded.
- Loop to read values and calculate the sum.
- Free the memory.
main.c
#include<stdio.h>
#include<stdlib.h>
int main( ) {
int n,i,*ptr,sum=0;
printf("Enter Number of Elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr==NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter Elements of array : ");
for(i=0; i < n; ++i) {
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum = %d",sum);
free(ptr);
return 0;
}
Expected Output
Enter the Number of Elements : 2 Enter Elements of array : 2 4 Sum = 6
Explanation of the Program
calloc()(Contiguous Allocation) is very similar tomalloc(), but it has two key differences.- First, it takes two arguments (number of blocks, size of each block) instead of one total byte count. Second, and most importantly, it automatically initializes all the allocated memory to 0, whereas
mallocleaves leftover garbage data in the memory.
Complexity
Time Complexity
O(n)
Space Complexity
O(n)