In this csharp example, we will learn how to create a function that Returns an Array in C# and we’ll find the sum of the element in an array using function.
We will get the value of array size and all the numbers from user.
Source Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public static int Add(int[] arr) { int total = 0; for (int i = 0; i < arr.Length; ++i) { total += arr[i]; } return total; } static void Main(string[] args) { int sizeArray = 0; Console.Write("Input the size of Array : "); sizeArray = Convert.ToInt32(Console.ReadLine()); int[] numbers = new int[sizeArray]; for (int i = 0; i < numbers.Length; i++) { Console.Write("Number {0} : ", (i + 1)); numbers[i] = Convert.ToInt32(Console.ReadLine()); } Console.WriteLine(); Console.WriteLine("The Sum is :" + Add(numbers)); //Console.WriteLine("www.csharp-console-examples.com"); Console.ReadKey(); } } |
Output: