Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Largest and smallest number in an array

Tags:

c#

This works perfectly...but when I use foreach instead of for this doesn't works. I can't understand for and foreach are same.

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[10];
            Console.WriteLine("enter the array elements to b sorted");
            for(int i=0;i<10;i++)
            {
                array[i] = Convert.ToInt32(Console.ReadLine());
            }
            int smallest = array[0];
            for(int i=0;i<10;i++)

            {
                if(array[i]<smallest)
                {
                    smallest=array[i];

                }
            }
            int largest = array[9];
            for(int i=0;i<10;i++)
            {

                if (array[i] > largest)
                {
                    largest = array[i];

                }
            }
            Console.WriteLine("the smallest no is {0}", smallest);
            Console.WriteLine("the largest no is {0}", largest);
            Console.Read();


        }
    }
}
like image 574
mhoni Avatar asked Feb 05 '11 12:02

mhoni


1 Answers

Why are you not using this?

int[] array = { 12, 56, 89, 65, 61, 36, 45, 23 };
int max = array.Max();
int min = array.Min();
like image 80
naveen Avatar answered Oct 16 '22 18:10

naveen