RocktheFries
RocktheFries

Reputation: 221

How to compare user input to an array, checking to see if its less that last input

I have to request user input for 10 different numbers. I have to see if the user input is less than the last number entered (which was added to an array). I'm having trouble comparing it, as my logic seems sound but for whatever reason it wont keep lower numbers inputted earlier in the loop. Maybe you guys can take a look and see where the issue lies in my if statement. The getNum() function just gets user input and returns it if your curious. Thanks in advance!

#include <stdio.h>   //including for the use of printf

/* == FUNCTION PROTOTYPES == */
int getNum(void);

/* === COMPILER DIRECTIVE - to ignore the sscanf() warning === */
#pragma warning(disable: 4996)


int main(void)
{   
// defining varibles
int myArray[11] = { 0 };
int counter = 0;
int indexTracker = -1;
int numInput = 0;
int lowestNum = 0;
int lowestNumPlace = 0;

// printing as to why I need 10 numbers
printf("I require a list of 10 numbers to save the world!\n");

// while loop
// while 'counter' is less than or equal to 9, loop
while (counter <= 9)
{
    // adding 1 to each varible, everytime the program loops
    indexTracker += 1;
    counter += 1;

    // printing to request a number, giving which number they are 
            // inputting
    // out of the list of 10
    // calling getNum() for input, saving the number into the array
    printf("Please enter a number for #%d: ", counter, "spot\n");
    numInput = getNum();
    myArray[indexTracker] = numInput;

    if (numInput <= myArray[indexTracker])
    {
        lowestNum = numInput;
        lowestNumPlace = indexTracker;
    }
}
// printing the lowest value and its index
printf("The lowest number is: %d at index [%d].", lowestNum, 
lowestNumPlace);

return 0;
}

Upvotes: 0

Views: 51

Answers (1)

Tim Randall
Tim Randall

Reputation: 4145

You're always assigning a new value to lowestNum

numInput = getNum();
myArray[indexTracker] = numInput;

if (numInput <= myArray[indexTracker])
{
    lowestNum = numInput;
    lowestNumPlace = indexTracker;
}

... because after doing A=B, B<=A will logically always be true.

Try this instead:

numInput = getNum();
myArray[indexTracker] = numInput;

if (numInput <= lowestNum)  // note, comparing to the lowest number, not the current one
{
    lowestNum = numInput;
    lowestNumPlace = indexTracker;
}

Upvotes: 2

Related Questions