C Program to sum of N integers in an array using pointers

February 2, 2022, Learn eTutorial

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

What is a pointer in C?

In this c program, we need to use the concept of pointers. A pointer is a variable with the address of another variable that may be in any primary data type. Simply pointer can hold the address of the variable. Using the pointer concept, we can have large values; also, we can access the variables value directly from the functions without the need for a return value.

What is dynamic memory allocation?

Here in this C program, we are also using the concept of Dynamic Memory Allocation to Allocate Memory space for the Pointers depends on the number of elements the user enters using " a=(int *) malloc(n*sizeof(int)) "

How to implement the 'sum' of integers of the array using pointers?

We use a for loop to calculate the Sum of all elements in the List using Pointer location increment by one and finally displaying the Sum of the elements in the Array. It is a simple C program to understand. We have the Equation Sn=n(n+1)/2 to calculate the Sum of 'n' integers, where 'n' is the number of Integers.

The main logic is to Declare the Integer variables first. Then declare a Pointer variable 'a'. Then read the size of the Array into 'N'. Then read the Array using a For loop by just incrementing the Pointer value by 1. By using another, For loop, find out the Sum of all the numbers like sum=sum + *(a+i). Then display the Sum of all elements.


STEP 1: Include the Header files to use the built-in functions in the C program.

STEP 2: Include the Header file 'malloc.h' to perform the Dynamic Memory Allocation.

STEP 3: Declare the integer variables i, n, sum

STEP 4: Declare the pointer 'a'.

STEP 5: Accept the size of the Array into n.

STEP 6: Allocate Memory Dynamically by using the Malloc() function.

STEP 7:  By using a for loop with the condition 'i < n' reads the elements of the Array.

STEP 8:  By using a for loop with the condition 'i < n' Calculate sum = sum + *(a+i).

STEP 9: Then display the Sum of all elements in the Array as Sum.

C Source Code

                                          #include <stdio.h>
#include <malloc.h>

void main() {
  int i, n, sum = 0;
  int * a;
  printf("Enter the size of array A\n");
  scanf("%d", & n);
  a = (int * ) malloc(n * sizeof(int)); /*Dynamic Memory Allocation */
  printf("Enter Elements of First List\n");
  for (i = 0; i < n; i++) {
    scanf("%d", a + i); /* increment the location of pointer to get next value */
  for (i = 0; i < n; i++) /*Compute the sum of all elements in the given array*/ {
    sum = sum + * (a + i);
  printf("Sum of all elements in array = %d\n", sum); /*display sum of the numbers in array */
} /* End of main() */


Enter the size of array A

Enter Elements of First List

Sum of all elements in array = 100