Sum of N elements in C using Pointer

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 you find anything incorrect? Let us know in the comments. Thank you!

Similar C programs

Leave a Comment

Your email address will not be published. Required fields are marked *