Click here to Skip to main content
15,881,139 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm doing a function that returns the index of the largest number in the array ;it's an easy function but I don't know why I'm getting stuck with code.whatever numbers I enter it returns an index number 0 although the largest number maybe in index number 6 or 7 for example.this is my code:
C#
int MAX_INT(int arr[],int s)
{
  int Max,temp;
  int i=0;
  temp=i;
  Max=arr[i];
  while(i<s)
  {
      if(Max>arr[i+1])
      {
          Max=arr[0];
          temp=0;
      }


      else{
          Max=arr[i+1];
          temp=i;
      }
     i++;
  }
  return temp;
}
int main()
{
  int arr[SIZE];
	for(int i=0;i<SIZE;i++)
	
		cin>>arr[i];
	
	cout<<MAX_INT(arr,SIZE);
}

Thank you
:)
Posted

Change your if statement ;

int MAX_INT(int arr[],int s)
{
    int Max,temp;
    int i=0;
    temp=i;
    Max=arr[i];
    while(i<s)>
    {
        if (Max < arr[i])
        {
            Max=arr[i];
            temp=i;
        }
        i++;
    }
    return temp;
}
 
Share this answer
 
Quicker, safer, simpler:
C++
#include <algorithm>
int MAX_INT(int arr[],int s)
{
    return std::max_element(arr, arr + s) - arr;
}

cheers,
AR
Edited to return index.
 
Share this answer
 
v2
Comments
Olivier Levrey 22-Feb-11 9:43am    
This returns the largest element in the array. Not its index.
Alain Rist 22-Feb-11 9:51am    
Right, corrected :)
Ba careful with your index:
int MAX_INT(int arr[],int s)
{
  int i=0;
  Max=arr[i];
  while(i<s)
  {
      //what will happen if i equals s - 1 ???
      if(Max>arr[i+1])
      {
          //...
      }
      i++;
   }
}


I suggest this:
int MAX_INT(int arr[], int s)
{
   if (s <= 0)
      return -1;
   int maxIndex = 0;
   int maxValue = arr[0];
   for (int i = 1; i < s; i++)
   {
      if (arr[i] > maxValue)
      {
          maxValue = arr[i];
          maxIndex = i;
      }
   }
   return maxIndex;
}
 
Share this answer
 
What is the purpose of the if/else ? A simple if block would work fine:

if (Max > arr[i])
{
   Max=arr[i];
   temp=i;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900