Cout an array element's index number

I need to display the subscript/index number of an element in an array, how do I do it?
thanks
Last edited on
Using a manual loop or std::find:

1
2
3
4
5
6
7
#include <algorithm>
[...]
const int arraySize=4;
int array[arraySize]={2,5,8,3};
auto it=std::find(array,array+arraySize,8);
if (it>=array+arraySize)cout << "Not found" << endl;
else cout << "Element found at index " << it-array  << endl;


http://www.cplusplus.com/reference/algorithm/find/
Will that give you 3(indx) or 8(pointer offset)? And is auto C++11?
It will give you the index of the first occurence of the element 8, so that's 2.

And is auto C++11?
Yes, you could replace auto with int*.
1
2
3
4
5
6
int MrArray[5] = {2, 3, 6, 10, 12};

for(int i = 0; i < 5; i++)
{
   cout << MrArray[i] << "\n";
}


A simple option.

EDIT: If that was the question?..
Last edited on
that will give you the elements in the indexes, but not the index number
Yeah, but you can add a simple if statement to search for a specific element.
So something like?

1
2
3
4
5
6
7
8
9
10
11
12
13
int MrArray[5] = {2, 3, 6, 10, 12}, TheNum;

cout << "Number to search for: ";
cin >> TheNum;

for(int i = 0; i < 5; i++)
{
   if(MrArray[i] == TheNum){
    cout << "You found " << TheNum << "at MrArray[" << i << "].";
   } else {
    cout << TheNum << "is not in MrArray[].";
   }
}
This will print "X is not in MrArray[]" at least four times, though.
EDIT:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const int SIZE = 5;
int MrArray[5] = {2, 3, 6, 10, 12}, TheNum, i;

cout << "Number to search for: ";
cin >> TheNum;

for(i = 0; i < SIZE; i++)
{
   if(MrArray[i] == TheNum){
       cout << "You found " << TheNum << "at MrArray[" << i << "].";
       i = SIZE+1;
       break;
   }
}

if(i == 4){
    cout << TheNum << "is not in MrArray[].";
}


Haha.. it does the job.
Last edited on
Nearly ;)
It should be if (i == SIZE)

i = SIZE+1; isn't necessary either, since you already have break.
Topic archived. No new replies allowed.