albert kim
albert kim

Reputation: 333

How do I match an input to an array index?

For this program I want to get an input from the user for a TV channel, which would be

int tv[] = {2, 4, 5, 6, 8};

and I want to prompt the user to input the TV channel they want so scanf for tv channel 4 which would be array index [1]. How do I match the scanned tv channel (4) to a new variable which would equal the array index of [1]?

Upvotes: 2

Views: 489

Answers (5)

Bhavik Shah
Bhavik Shah

Reputation: 5183

Searching every time in an array could be expensive(in my opinion if you have a large array) one other solution could be that you can have another array which would map you to the right index

for example,

int tv[] = {2, 4, 5, 6, 8};
int mapping[]={-1,-1,0,-1,1,2,3,-1,-1,4};
tv[mapping[channelNumber]]//getting the actual value

this would take additional space but can give you performance improvment

Upvotes: 0

CCoder
CCoder

Reputation: 2335

The easier way is to search the array through using some searching algorithm. If your array is HUGE, then you may want to look at a c++ container called as map. If you create a map, then you can do the association you mentioned in O(1).

Upvotes: 1

m4n1c
m4n1c

Reputation: 127

I believe the question is a simple case of searching. You can probably do a linear search if the channels are not in order or else make use of binary search logic for finding the channel. If you dont want that either then make use of hashing concept. But that will increase the size of the array but it help u to find the element very easily.

Hope that answers to your question.....

Upvotes: 1

Dileep
Dileep

Reputation: 2425

Do a simple linear search, where element ( channel number here) is sequentially searched in the array

int channelnumber,arrayindex;
printf("\n Enter the channel number");
scanf("%d",&channelnumber)
for(i=0;i<5;i++)
{
     if(tv[i]==channelnumber)
     {
        arrayindex=i;
        break;
     }
}

Upvotes: 1

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27632

Read the channel number from the user, and loop through the array to find the place where that channel number is.

Upvotes: 2

Related Questions