What Index is in Vectors C++

Hello ! I have this code about finding the max from a vector , i do understand it , but in another code , i have to find the max in vector and his index , i really dont understand from where the index coming when it print me the result , can you explain me from where the Index come:

Here Code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
using namespace std;
int main(){
int N;
cout<<"N=";cin>>N;
int a[1000];
int i;
for(i=0;i<N;i++){
cout<<"nr=";cin>>a[i];

}
int max=0;
int indexMax=0;
for(i=1;i<N;i++)
if(a[i]>max){
max=a[i];
indexMax=i;
}
cout<<"Maxim= "<<max<<" index= "<<indexMax;
return 0;
}
Edit & Run




I cant understand from where the index come.
Sry my english
It comes from this line:

indexMax=i;

The value of i is set in the loop:

for(i=1;i<N;i++)
First a note: code tags <> make posts more readable. See http://www.cplusplus.com/articles/jEywvCM9/

After all, it seems that you did copy-paste that code from another post on this forum and that post had the tags.

Here is a slightly different version:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>

int main() {
  using std::cout; using std::cin;
  int N;
  cout << "N=";
  cin >> N;
  if ( N < 1 ) N = 1;
  constexpr int M {1000};
  if ( M < N ) N = M;
  int a[M];
  int i = 0;
  while ( i=0; i<N; ++i ) {
    cout << "nr=";
    cin >> a[i];
  }
  int indexMax = 0;
  for ( i=1; i<N; ++i ) {
    if ( a[indexMax] < a[i] ) {
      indexMax=i;
    }
  }
  cout << "Maxim= " << a[indexMax] << " index= " << indexMax;
}

Was MikeyBoy's hint enough for you to understand both versions?
Topic archived. No new replies allowed.