find largest number position

I have to write program using an array enter numbers and then determine largest number's position, For example if i enter 5 7 9 1 6 it should return 2 since 9 is largest number. this what i have,but it always returns -1

#include <iostream>
#include <fstream>
using namespace std;
const int SIZE=100;
ofstream output("output.doc");
int main()
{
int n,pos=-1;
int number[SIZE];
cout<<"How many numbers would you like to enter?"<<endl;
cin>>n;
cout<<"Please enter the numbers"<<endl;

int largesofar=number[0];
for(int i = 1; i <=n && pos==-1; i++)
{
cin>>number[i];

if(largesofar<number[i])
{
largesofar=number[i];
pos=i;
}
output <<number[i] << endl;

}

cout<<pos<<endl;

output.close();
system("pause");
return 0;
}
There are many wrongs in your code.Such as ;

int largesofar=number[0];
you haven't get any value for number[0] yet.Delete it.

Also your loop condition is wrong.
Change it as;
for(int i = 0; i <n ; i++)

Your loop shall look like this ;

1
2
3
4
5
6
7
8
9
10
11
12
13
for( int i = 0 ; i < n ; i++ )
{
   cin >> number[i];
   if( i == 0 )
   {
     largesofar = number[i];
     pos = 0 ;
   }
   else if(number[i] > largesofar) {
     largesofar = number[i];
     pos = i ;       
   }
}


I have'nt compiled this, but your code shall look similar to this.
Last edited on
thank you very much now it work
one more question

i tried to write the program calling function but it always returns 0

#include <iostream>
using namespace std;
int poslarge(int number[], int n);
const int SIZE=100;
int main()
{

int n,number[SIZE],pos;
cout<<"How many numbers would you like to enter?" << endl;
cin>>n;
cout<<"Input a number"<<endl;
for(int i=0; i<n; i++)
{
cin>>number[i];
pos=poslarge(number,n);
}
cout<<"The position that had the largest number is "<<pos<<endl;

return 0;
}
int poslarge(int number[],int n){
int pos,k,largesofar;
for( int i = 0 ; i < k ; i++ )
{
cin >> number[i];
if( i == 0 )
{
largesofar = number[i];
pos = 0 ;
}
else if(number[i] > largesofar) {
largesofar = number[i];
pos = i ;
}
}
return pos;
}
Topic archived. No new replies allowed.