C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# Passing Array to FunctionIn C#, to reuse the array logic, we can create function. To pass array to function in C#, we need to provide only array name. functionname(arrayname);//passing array C# Passing Array to Function Example: print array elementsLet's see an example of C# function which prints the array elements. using System; public class ArrayExample { static void printArray(int[] arr) { Console.WriteLine("Printing array elements:"); for (int i = 0; i < arr.Length; i++) { Console.WriteLine(arr[i]); } } public static void Main(string[] args) { int[] arr1 = { 25, 10, 20, 15, 40, 50 }; int[] arr2 = { 12, 23, 44, 11, 54 }; printArray(arr1);//passing array to function printArray(arr2); } } Output: Printing array elements: 25 10 20 15 40 50 Printing array elements: 12 23 44 11 54 C# Passing Array to Function Example: Print minimum numberLet's see an example of C# array which prints minimum number in an array using function. using System; public class ArrayExample { static void printMin(int[] arr) { int min = arr[0]; for (int i = 1; i < arr.Length; i++) { if (min > arr[i]) { min = arr[i]; } } Console.WriteLine("Minimum element is: " + min); } public static void Main(string[] args) { int[] arr1 = { 25, 10, 20, 15, 40, 50 }; int[] arr2 = { 12, 23, 44, 11, 54 }; printMin(arr1);//passing array to function printMin(arr2); } } Output: Minimum element is: 10 Minimum element is: 11 C# Passing Array to Function Example: Print maximum numberLet's see an example of C# array which prints maximum number in an array using function. using System; public class ArrayExample { static void printMax(int[] arr) { int max = arr[0]; for (int i = 1; i < arr.Length; i++) { if (max < arr[i]) { max = arr[i]; } } Console.WriteLine("Maximum element is: " + max); } public static void Main(string[] args) { int[] arr1 = { 25, 10, 20, 15, 40, 50 }; int[] arr2 = { 12, 23, 64, 11, 54 }; printMax(arr1);//passing array to function printMax(arr2); } } Output: Maximum element is: 50 Maximum element is: 64
Next TopicC# Multidimensional Arrays
|