C# Passing Array to Function
We can create a function in C#, to reuse the logic of an array. Only the array name is needed to pass an array to function in C#.
Syntax:
function_name(array_name);
Example 1: Printing array elements.
using System; public class Example { static void display(int[] a) { Console.WriteLine("Array elements:"); for (int i = 0; i < a.Length; i++) { Console.WriteLine(a[i]); } } public static void Main(string[] args) { int[] a1 = { 1, 3, 5, 7, 9 }; int[] a2 = { 2, 4, 6, 8, 10 }; display(a1); //passing array to function display(a2); } } |
Output:
Explanation:
In the above example, we are creating two arrays and a C# function to print the array elements of each array.
Example 2: Printing minimum number.
using System; public class Example { static void Min(int[] a) { int min = a[0]; for (int i = 1; i < a.Length; i++) { if (min > a[i]) { min = a[i]; } } Console.WriteLine("Minimum element is: " + min); } public static void Main(string[] args) { int[] a1 = { 3, 5, 1, 7, 9 }; int[] a2 = { 4, 6, 8, 10, 2 }; Min(a1); //passing array to function Min(a2); } } |
Output:
Explanation:
In the above example, we are creating two arrays and a C# function to print the minimum number in each array.
Example 3: Printing maximum number.
using System; public class Example { static void Max(int[] a) { int max = a[0]; for (int i = 1; i < a.Length; i++) { if (max < a[i]) { max = a[i]; } } Console.WriteLine("Maximum element is: " + max); } public static void Main(string[] args) { int[] a1 = { 3, 5, 9, 1, 7 }; int[] a2 = { 4, 6, 8, 10, 2 }; Max(a1); //passing array to function Max(a2); } } |
Output:
Explanation:
In the above example, we are creating two arrays and a C# function to print the maximum number in each array.