Noobgrammer
Noobgrammer

Reputation: 5

Program not working properly when inputting a 2-digit number

const ps = require("prompt-sync");
const prompt = ps();
console.log("\nFinding The Maximum Number In The Array");
console.log("---------------------------------------");
let length = prompt("Enter the length of the array: ");
let temp = 0;
let maxnum;

    let array = [];
    for(let i=0; i<length;i++){
        let num = prompt(i+":");
        array[i] = num;
}

console.log("\nlength: " + length);
for(let o=0; o < length ; o++ ){

        if(array[o] > temp){
            temp = array[o];
        }
        if(o == (length-1)){
           maxnum = temp;
           console.log("\ncurrent max " + maxnum);
        }
    }

console.log("The maximum number is: "+ maxnum);

Works properly when comparing 1-digit numbers; 1,2,3,7 for example. Its output is 7 for the max number. But when adding 10 to the list, the program will still output 7.

Upvotes: 0

Views: 344

Answers (3)

Srinivas Naik
Srinivas Naik

Reputation: 19

You have to store the values as an integer in your array while accepting input at the prompt. Or else the values will be considered as type string by default.

You can use parseInt(yourInput);.

Upvotes: 0

William Forty
William Forty

Reputation: 252

Because prompt gets you a string, it is comparing the values alphabetically. Just as the character "C" could be considered greater than the character "A", the text character "7" is also greater than the text character "1". So just as the word "APPLE" would be sorted alphabetically before "CAT", even though "APPLE" is longer, so is the text string "10" sorted alphabetically before the text string "7". In fact, the text "1000000" would also come before the text "7" when sorted alphabetically.

To solve, you must convert the text string to a number first, which can be achieved with parseInt(). A convenient place to do this would be immediately after you retrieve the string input from the user, as in array[i] = parseInt(num);.

Upvotes: 0

C3roe
C3roe

Reputation: 96306

prompt gets you string values, and when you compare the string value 10 to 7, then 7 is considered the greater one, because string comparison happens character by character, from left to right.

Use array[i] = parseInt(num); to convert those string values into actual integer values first.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Upvotes: 1

Related Questions