Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

Program:

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

#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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

One Dimensional Array Programs / Examples in C programming language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to add two dynamic arrays... >>
<< C program to find the first repeated element in an...