C Sharp Program To Find Largest Number In An Array Easy Way

C# program to find largest number in an array with simple logic and example and test cases.

Example:
Input Array: 2 6 4 8 9
Output: 9

LOGIC:

  • Create an integer variable and store first element of the array into it, assuming this is largest value.
  • Traverse the array using for a loop from location 1 to array length -1. 0th location we have already stored in largest variable.
  • Check if current element is larger than value stored in largest variable. If it is larger, then assign the largest variable with current array location value.
  • Once loop is over, largest variable contains largest/max value.

C# Program To Find Largest Number In An Array

Code

using System;
 /* --------------------------------------------------
* C# Program to find largest number in Array
*/

    /* --------------------------------------------------
* C# function to find largest element
* in an integer array
*
* @ parameters: 
* int arr : It accept base address of int array
* 
*
*
* @ return : It returns the largest / maximum
* value from array
*/
    class Program
    {
        static void Main(string[] args)
        {
            ///* Enter size of the int array */
            Console.WriteLine("Please enter the size of the array");
            int size;
            bool flag = int.TryParse(Console.ReadLine(), out size);

            if(flag==false)
            {
                Console.WriteLine("Invalid number");
                return;

            }
            flag = false;

            Console.WriteLine("Please enter {0} elements into array",size);
            int[] arr=new int[size];

            ///* Input array elements */
            for (int i = 0; i < size; i++)
            {
                flag = int.TryParse(Console.ReadLine(), out arr[i]);
                if(flag==false)
                {
                    Console.WriteLine("In valid Number");
                    return;
                }
            }

            ////Call function to get largest number
            int largesnumber = PrintLargeNumber(arr);

            Console.WriteLine("The Largest Number in the array is {0}", largesnumber);

            

        }

        static int PrintLargeNumber(int[] arr)
        {
            int largestNumber=arr[0];
            for (int i = 1; i < arr.Length; i++) { /* If current element is larger, then assign * value to largest variable. */ if(arr[i]>largestNumber)
                {
                    largestNumber = arr[i];
                }
            }

            ////Return the largest number
            return largestNumber;
        }
    }

Output

Please enter the size of the array
6
Please enter 6 elements into array
5
3
6
2
4
8
The Largest Number in the array is 8

Related Posts