C# program to find a maximum number from the array.


Introduction:

In this post, we are going to implement a simple program, which requires a simple logic called "Comparison". Don't get shocked this is true we are going to implement a simple program which compare array members and give us the largest number among all the numbers as output.

Background:

To implement this program, you must be aware of an array, how to initialize an array? and how to compare to members of an array? I guess that you are familiar with an array and moving towards implementation.

And if someone is not aware to an array then they can refer this link. Array

Implementation:

Implementation of this program is quite simple we just need two for loops one to ask from input from a user and store it in an array and the second to compare the members and find the max one.But here in this program I have used one extra for loop to display the members of an array, by the way, it is not compulsory.





 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
31
32
33
34
35
36
37
38
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = new int[5];
            int i, max = 0;
            Console.WriteLine("Enter the 5 number:");
            for (i = 0; i <= 4; i++)
            {
                arr[i] = Convert.ToInt16(Console.ReadLine());
            }

            Console.WriteLine("Entered Array Values Are:");
            for (i = 0; i <= 4; i++)
            {
                Console.WriteLine(arr[i]);
            }


            for (i = 0; i <= 4; i++)
            {
                if (arr[i] > max)
                {
                    max = arr[i];
                }
            }
            Console.WriteLine("Maximum Number is:" + max);
        }
    }
}

Here I am asking for just five numbers because I have created an integer array of 5 elements.You can specify your own size by just replacing 5 with a size you want.If we talk about logic then I can say that first I have taken integer variable m to store maximum number and initiate it to 0, now when the if condition checks that if there is a number greater than the maximum number then make it maximum and store it in m.This continues until all the members of the array are not compared and finally print the value of m on the console as the maximum value.

As of in this post today we have seen quite a simple program, in my next post I will come up with an interesting program to share with you.

Please Do share, comment, and subscribe my blog.Enjoy coding!!!!

Comments