Home »
C programs »
C user-defined functions programs
C program to find sum of the array elements (pass an integer array to a function and return the sum)
In this C program, we are going to learn how to pass an integer array (one dimensional array) to a user defined function and return sum of all elements?
Submitted by IncludeHelp, on March 20, 2018
Problem statement
Given an array of integers (one dimensional array) and we have to find sum of all elements using user define function in C.
Here, we will pass array to the function and function will return the sum of the elements.
Function Declaration
Here is the function that we have used in the program,
int sum_of_elements(int *arr , int n)
Here,
- int is the return type of the function i.e. function will return an integer value that will be the sum of the all array elements.
- sum_of_elements is the name of the function.
- int *arr is the integer pointer that will represent the integer array i.e. hold the based address of integer array which will be passed while function calling in the main() function.
- int n is the total number of elements.
Function Calling
Function calling statement,
total = sum_of_elements(array,9);
Here,
- total is the name of an integer variable declared in main() which will store the sum of the elements (returned by the function).
- array is the name of the integer array.
- 9 is the total number of elements.
Program to find the sum of all array elements using function in C
/*
* C program to a pass integer array elements to
* a function and return the sum of all elements
*/
#include <stdio.h>
// function to calculate the sum of array
// elements
int sum_of_elements(int *arr , int n)
{
int i=0,sum=0;
for(i=0; i<n ; i++)
{
sum = sum + arr[i];
}
return sum;
}
// main function
int main()
{
int total = 0;
int array[10] = {1,2,3,4,5,6,7,8,9};
// Passing array to Function
total = sum_of_elements(array,9);
printf("\nThe sum of all array elements is : %d",total);
return 0;
}
Output
The sum of all array elements is : 45
C User-defined Functions Programs »