C Program to find sum of array elements using pointers

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

What are the pointers?

In this program, we have to find the sum of elements of an array using pointers. For that, we have to know something about pointers. We define pointers as a variable that stores the memory address of another variable located in memory. A pointer concept is beneficial in the call by reference method of passing parameters to a function. A pointer can be declared as int *p; where *p is the pointer of type integer.

How to calculate the sum using pointers and functions?

In this c program, what we need is to calculate the sum of all elements of an array using function and pointers. So we import the header libraries to use the inbuilt functions in the program. Now declare a static array and declares a function prototype.

Now we already have the values in the array; we call the function to calculate the sum. As we are using pointers, we do not need to pass the result by old methods; it gets automatically transferred to the function as we are using the memory location. In the function, we calculate the sum of all elements using for a loop. It is a simple c program to understand. Here for loop is used.

ALGORITHM

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

STEP 2: Declare the variable sum as integer Array[5] as a static integer array.

STEP 3: Define the function int addnum(int *ptr).

STEP 4: Calculate sum=addnum(array).

STEP 5: Display Sum of all array elements as a sum.

Function int addnum(int *ptr)

STEP 1: Declare the variable index, total as an integer.

STEP 2: Using a for loop with the condition index<5 calculate total=total+*(ptr+index).

STEP 3: Return total.

C Source Code

                                          #include <stdio.h>

void main() {
  static int array[5] = {
    200,
    400,
    600,
    800,
    1000
  };
  int sum;
  int addnum(int * ptr); /* function prototype */
  sum = addnum(array);
  printf("Sum of all array elements =%d\n", sum);
} /* End of main() */
int addnum(int * ptr) {
  int index, total = 0;
  for (index = 0; index < 5; index++) /* calculating sum in the for loop */ {
    total += * (ptr + index);
  }
  return (total);
}
                                      

OUTPUT

Sum of all array elements =  3000