ADVERTISEMENT
ADVERTISEMENT

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

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.

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 statement,

total = sum_of_elements(array,9);

Here,

  1. total is the name of an integer variable declared in main() which will store the sum of the elements (returned by the function).
  2. array is the name of the integer array.
  3. 9 is the total number of elements.
ADVERTISEMENT

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.