# C TUTORIAL
# C PROGRAMS
Pointers Examples
➤ Pointer Basic Examples
➤ Dynamic Memory Allocation
➤ Read Write Array with Pointer
➤ Sum Avg of Array with Pointer
➤ Sort Array with Pointer
➤ Search in Array using Pointer
➤ Sum of N Numbers
➤ Largest Number by DMA
Others
➤ C Program Without Main()
➤ Hello World Without ;
➤ Process & Parent Process ID
➤ C Program Without Header File
➤ void main(), main() vs int main()
➤ fork() function in C
➤ Why gets function is dangerous
➤ Undefined reference to sqrt
# C PROGRAMS
Pointers Examples
➤ Pointer Basic Examples
➤ Dynamic Memory Allocation
➤ Read Write Array with Pointer
➤ Sum Avg of Array with Pointer
➤ Sort Array with Pointer
➤ Search in Array using Pointer
➤ Sum of N Numbers
➤ Largest Number by DMA
Others
➤ C Program Without Main()
➤ Hello World Without ;
➤ Process & Parent Process ID
➤ C Program Without Header File
➤ void main(), main() vs int main()
➤ fork() function in C
➤ Why gets function is dangerous
➤ Undefined reference to sqrt
Write a C program to find the sum of N numbers/elements entered by the user using dynamic memory allocation i.e. pointer. In the first method, we will use malloc() and free(). In the second method, we will use calloc() and free().
C Program to Find the Sum of N elements entered by the user using malloc() and free() – Pointer
#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): 3
Enter elements :
10
20
30
Sum = 60
Using calloc() and free()
#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 total number of elements(1 to 100): 4
Enter elements :
1
20
3
5
Sum = 29
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!
Similar C programs