Hello to all frndz! i want to write a program in which i have stored some integer elements in an array and i want that my program searches for the largest integer and displays it. for example if i have some integers in my array like 23, 38, 81, 12. then my program should display "Largest integer is 81". I have wrote code for this program but it gives wrong output. the code for my program is as follows:

#include<iostream.h>
main()
{
 int arr[4]={23,38, 81,12};
 int i;                          // counter variable
 for(i=0;i<=4;i++)
 {
      if(arr[i]>(arr[i+1]))
      {
         cout<<"largest integer is"<<arr[i]<<endl;
      }  
         else
         cout<<"largest integer is "<<arr[i+1]<<endl;
} 
system("pause");
}                          
  1. The loop for(i=0;i<=4;i++) should be for(i=0;i<4;i++)
  2. You should set a 'largest' variable as found and then output that after the loop has terminated. Following is how to do that.
  3. You also have a bunch of other issues that should make your compiler throw up...

    #include<iostream.h>
    int main(void)
    {
        int arr[4]={23,38, 81,12};
        int biggest = 0;
        for(i=0; i < 4; i++)
        {
            if(arr[i]>biggest)
            {
                biggest = arr[i];
            }
        }
        cout << "largest integer is" << dec << biggest << endl;
    }
    

Edited 2 Years Ago by rubberman

You are running out of the bounds of the array using i<=4 in your for loop. if(arr[i]>(arr[i+1])) will also run out of bounds when you are at the end of the array. You also don't want the print to be in the loop since it would print every time it finds a larger element. The most common way of findind the max of an array is as follows (pseudocode):

array a = {23,38, 81,12}
int max = a[0]  -- set max to the start of the array

for i = 1 to i < 4  -- start position 1 since you already have a[0] in max
{                   -- use < size of array and not <= since arrays are 0 index based
    if (a[i] > max)
        max = a[i]
}

display max

Try out the following code:

#include<iostream.h>
int main(void)
{
    int arr[4]={23,38, 81,12};
    int biggest = a[0];
    for(i=1; i < 4; i++)
    {
        if(arr[i]>biggest)
          biggest = arr[i];

    }
    cout << "largest integer is" << dec << biggest << endl;
}
Comments
This handles the case where all the numbers are negative. Good catch, but you should have mentioned that.

NathanOliver, haven't you noticed the minor changes that I have made in the following lines of rubberman?:

int biggest = 0;
for(i=0; i < 4; i++)

Actually, dinad's change is legitimate since there can be negative numbers in the array, and if they all are, then my code would not provide the correct answer. :-)

This article has been dead for over six months. Start a new discussion instead.