Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to calculate sum of all elements of array using calloc function

C Code Example — Structure Programs

ADVERTISEMENT

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

  1. Read n elements.
  2. Allocate memory using ptr = (int*) calloc(n, sizeof(int)).
  3. Check if allocation succeeded.
  4. Loop to read values and calculate the sum.
  5. 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 to malloc(), 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 malloc leaves leftover garbage data in the memory.

Complexity

Time Complexity O(n)
Space Complexity O(n)
ADVERTISEMENT