Wednesday, April 12, 2017

How to find the max in array of integers?


To find the max integer value we need to loop through the array and then assume last element is the greatest and the compare the current value. If cur is greater then last then max=cur



Java
/*
   * Program to find the max integer of an array
   */
  int  [] intarr={1,50,60};
  //Check if the array length is zero
  if(intarr.length==0)
  {
   //int arrayLength=intarr.
   System.out.println("Array length is zero");
    
  }
  else
  {
   int max=intarr[intarr.length-1];
   for(int i=0;i<intarr.length-1;i++)
   {
    
    int curr=intarr[i];
    if (curr >max)
    {
     max=curr;
    }
   }
   System.out.println(max);
  }

In C#
 class FindMaxIntInArray
    {
        public static int FindMax()
        {
            int [] arr = { 1, 70, 50 };

            if (arr.Length == 0)
                return 0;
            var max = arr[arr.Length - 1];
            for (int i = arr.Length - 1; i >=0; i--)
            {
                if(arr[i] > max)
                {
                    max = arr[i];
                }
            }
            return max;
        }
    }

No comments:

Post a Comment