Feb 2, 2012 at 10:16pm UTC
I need to display the subscript/index number of an element in an array, how do I do it?
thanks
Last edited on Feb 2, 2012 at 10:30pm UTC
Feb 2, 2012 at 11:52pm UTC
Will that give you 3(indx) or 8(pointer offset)? And is auto C++11?
Feb 3, 2012 at 12:01am UTC
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 Feb 3, 2012 at 12:04am UTC
Feb 3, 2012 at 12:06am UTC
that will give you the elements in the indexes, but not the index number
Feb 3, 2012 at 12:12am UTC
Yeah, but you can add a simple if statement to search for a specific element.
Feb 3, 2012 at 12:41am UTC
This will print "X is not in MrArray[]" at least four times, though.
Feb 3, 2012 at 12:50am UTC
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 Feb 3, 2012 at 12:57am UTC
Feb 3, 2012 at 1:03am UTC
Nearly ;)
It should be if (i == SIZE)
i = SIZE+1; isn't necessary either, since you already have break .