Array with Fuction, Passing Array to Fuction
Till now we have learnt about array declaration, initialization, accessing array elements and some programs based on array. In this chapter we will learn how to user array with function like how to pass array to a function as argument , and we will also see some good programs based on array and function
What is output..?
Important
In above example the function myfun() takes an input of int type, where variable a and b called as
Array as Argument Rules
There are two rules, which must be followed while passing array as a function’s argument. The rules are listed below.
- Data type of argument array ( sending array ) and data type of parameter array ( receiving array ) must be same.
- Size of argument arry and size of parameter array must be same.
Syntax
Note: Above Syntax
send_arry → is Argument
r_arry → is Parameter
- Data type of send_array and r_array must be same, in systax data type of both array is int.
- size of both array must be same, in above syntax the size of both array is n.
Passing One – Dimensional Array to a Function
In a same way how we pass value of variables while calling a function we can also pass array as value which is an array.
Output
Student Marks are
68
82
95
71
73
87
91
Explanation
- In above example, in main() fuction we have declared an int type array marks of size 7 with predefined values.
- Now we are calling function getMarks(), which accept an input int type array of size 7, so in main() function while calling getMarks() we have passed marks array to the function.
- Function getMmarks() parameter variable array see_marks get assigned by the value of marks array.
Note: In One-Dimensional Array it is not necessary to define the size of parameter array, if we don’t define the size of parameter array then it’s automatically will assigned with the size of argument array. But in case of multidimensional array the size of parameter array must be declared.
Output
Passing Two: Dimensional Array to a Function
Just like One: Dimensional Array we can pass Two – Dimensional array to a function, let’s see it by taking an example.
Note: Size of Argument and Parameter must be declared and should be same.
Q. Find the sum of all elements of int type array, the size of array is 2*3 and array elements are predefined.
Output
Conclusion
There are only two things needs to be care while passing an array to a function.
- Data Type should be same.
- Size of argument array and parameter array should be same.
Similarly One and Two dimensional array we can pass N – Dimensional array to a function, just follow those two rules.