Learn about Sum of N elements in C using Pointer Using calloc() and free() in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.
Contents
Sum of N elements in C using Pointer Using calloc() and free()
Here, we have to allocate numbers using dynamic allocation i.e., Pointers. In below code, calloc() and free() functions are used.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int num, i, *ptr, sum=0;
printf("Enter total number of elements(1 to 100): ");
scanf("%d",&num);
// memory allocated using malloc()
ptr= (int*) calloc (num, sizeof(int));
if(ptr==NULL)
{
printf("Memory not allocated.");
return EXIT_FAILURE;
}
printf("Enter elements :\n");
for(i=0;i<num;i++)
{
scanf("%d",ptr+i);
sum += *(ptr+i);
}
printf("Sum= %d",sum);
free(ptr);
return 0;
}
Output:
Enter number of elements(1 to 100): 5
Enter elements :
4
5
3
7
8
Sum= 27
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Codes :
C Program to Find the Sum of N elements entered by the user using malloc() and free() – Pointer
Search Element in Array Using Pointer & Function in C