-2

This is my 2d array with available speeds listed. this code I must keep. If my user enters 75349 as their clock speed input, how will I be able to recognize that speed and return the value of the row index ?... which is row 2 int the 2d array because it lies between 7500- 14900

int UserClockSpeedInput;

const uint32 SpeedTable[5][2] {
{15000, 99990}, //between 15k - 99.99k
{7500, 14900}, //between 7.5k - 14.9k
{3500,7400},
{1900,3400},
{6000,1800}
}

I want to return the row index of whatever value the user entered, these are the set values I already set in place. They are not allowed to enter any other values

for(i=0;i<5;i++)
{
    for(j=0;j<2;j++)
    { 

 //not sure of what to do from here.

2 Answers2

0

how will I be able to recognize that speed and return the value of the row index

Solution :

You can simply achieve it by using the following for loop

    int number; //variable to hold user's input

    //scanning user's input
    printf("enter any number : ");
    scanf("%d",&number); 

    //for loop to determine position
    for (int index = 0; index < 5; index++)
    {
        if( (number >= SpeedTable[i][0]) && (number <= SpeedTable[i][1]) )
        {
            break;
        }
    }

    //printing index
    printf("return index value : %d ",i);

Suggestions :

firstly,

  • I think your last element of the 2-D array must not be {6000,1800},
  • I think it must instead be {600,1800}

and,

  • Don't use void main(). to know why, see this : click
  • Instead use int main(void). to know why, see this : click

so altogether your code would be :

#include <stdio.h>

int main(void){

    const unit32 SpeedTable[5][2] = {
        {15000, 99990}, //between 15k - 99.99k
        {7500, 14900}, //between 7.5k - 14.9k
        {3500,7400},
        {1900,3400},
        {600,1800} //between 0.6k - 1.8k
    };

    int number;

    printf("enter any number : ");
    scanf("%d",&number);

    int i;

    for (i = 0; i < 5; i++)
    {
        if( (number >= SpeedTable[i][0]) && (number <= SpeedTable[i][1]) )
        {
            break;
        }
    }

    printf("return index value : %d ",i);

}
Community
  • 1
  • 1
Cherubim
  • 5,287
  • 3
  • 20
  • 37
-1

You want to check the input against the upper and lower bounds that you have provided in your arrays. You should check to see if the input is greater than the 1st element, and less than the 2nd element.

#include <stdio.h>

void main(){
    const int SpeedTable[5][2] = {
        {15000, 99990}, //between 15k - 99.99k
        {7500, 14900}, //between 7.5k - 14.9k
        {3500,7400},
        {1900,3400},
        {6000,1800}
    };

    int user_input = 7534;

    int i;

    for (i = 0; i < sizeof(SpeedTable)/ (2 * sizeof(int)); i++){
        if (SpeedTable[i][0] < user_input && SpeedTable[i][1] > user_input){
            break;
        }
    }

    printf("%d\n", i);
}
ritlew
  • 1,622
  • 11
  • 13