C program to calculate the sum of array elements using pointers as an argument

Here, we are going to learn how to calculate the sum of array elements using pointers as an argument in C programming language?
Submitted by Nidhi, on July 10, 2021

Problem statement

Here, we will create a user define function that accepts an array in an integer pointer, and then we will access array elements using the pointer and calculate the sum of all array elements and return the result to the calling function.

Calculating the sum of array elements using pointers as an argument in C

The source code to calculate the sum of array elements using pointers as an argument is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

C program to calculate the sum of array elements using pointers as an argument

// C program to calculate the sum of array elements
// using pointers as an argument

#include <stdio.h>

int CalculateSum(int* arrPtr, int len)
{
    int i = 0;
    int sum = 0;

    for (i = 0; i < len; i++) {
        sum = sum + *(arrPtr + i);
    }

    return sum;
}

int main()
{
    int intArr[5] = { 10, 20, 30, 40, 50 };
    int sum = 0;

    sum = CalculateSum(intArr, 5);

    printf("Sum of array elements is: %d\n", sum);

    return 0;
}

Output

Sum of array elements is: 150

Explanation

In the above program, we created two functions CalculateSum() and main() function. The CalculateSum() function is used to accept integer array and assigned to the pointer. Then we accessed array elements and calculated the sum of array elements and returned the result to the main() function.

In the main() function, we read an array of 5 integers. Then we called the CalculateSum() function and got the sum of array elements and printed the result on the console screen.

C One-Dimensional Array Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.