Write a program in C# to get the largest element of an array using a function.
Test Data:
Input the number of elements to be stored in the array: 5
Input 5 elements in the array:
element - 0: 1
element - 1: 2
element - 2: 3
element - 3: 4
element - 4: 5
Expected Output:
The largest element in the array is: 5
using System;
using System.Collections.Generic;
using System.Globalization;
namespace App
{
class Program
{
static int getLargestElementArray(int[] elements)
{
int largestElement = elements[0];
for (int i = 1; i < elements.Length; i++)
{
if (elements[i] > largestElement) {
largestElement=elements[i];
}
}
return largestElement;
}
static void Main(string[] args)
{
Console.Write("Input the number of elements to be stored in the array: ");
int number = int.Parse(Console.ReadLine());
int[] elements = new int[number];
Console.WriteLine("Input {0} elements in the array:", number);
for (int i = 0; i < elements.Length; i++)
{
Console.Write("element - {0}: ", i);
elements[i] = int.Parse(Console.ReadLine());
}
int largestElement = getLargestElementArray(elements);
Console.WriteLine("The largest element in the array is: {0} ", largestElement);
Console.ReadLine();
}
}
}
Comments
Leave a comment