Learn about C Program to Find the Sum of N elements entered by the user using malloc() and free() – Pointer in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.
C Program to Find the Sum of N elements entered by the user using malloc() and free() – Pointer
C program that uses dynamic memory allocation, i.e. pointers, to find the sum of N numbers entered by the user. We shall use malloc() and free() in the first way (). We shall use calloc() and free in the second approach ().
Source code:
#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*) malloc (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 total number of elements(1 to 100): 4
Enter elements :
5
15
20
40
Sum = 80
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Codes :
Search Element in Array Using Pointer & Function in C
C Program to Sort List of Array Elements Using Function & Pointer