1

My friend asked me to help him with homework, and I'm stuck. Here is assignment:

user must enter in first prompt box number of elements in array. Then, he will get prompt box for each number to enter. Now, output must be greatest number in array. But that simply doesn't work. With my code below, I always get the element who has greatest first digit. (it's doesn't matter if number is negative or positive, code doesn't work as it should)

Here is my code (it even doesn't work in jsfiddle, just in my file)

<button onclick="duzinaNiza()">Do it!</button>

and here is JavaScript

function duzinaNiza() {
    var brClanova = prompt("Enter the number of array elements:");

    if (brClanova > 0) {
        var niz = new Array();

        for (i=0; i<brClanova; i++) {
            var redniBr = i+1;
            niz[i] = prompt("Enter "+ redniBr +". array number:");
            \\ prompt for geting each array element
        }


        var maximum = niz[0];

        for (a=0; a<brClanova; a++) {

            if (maximum < niz[a]) {
                maximum = niz[a];
            }
        }

        document.write("Greatest value in array is: " + maximum);   
    }
}

My friend's proffesor doesn't want to use functions for sorting arrays, this must be done with loops.

P.S. Yeah, I know... But don't ask about document.write thing, it must be printed in that way...

Gray
  • 7,050
  • 2
  • 29
  • 52
Miljan Puzović
  • 5,840
  • 1
  • 24
  • 30

7 Answers7

1

That is because the input is a String, you have to parse it to a Integer. Like:

niz[i] = parseInt(prompt("Enter "+ redniBr +". array number:"), 10);
Ian
  • 50,146
  • 13
  • 101
  • 111
Niels
  • 48,601
  • 4
  • 62
  • 81
  • I thought that input is a string, but i was not sure. So, there is no way to get number from prompt without `parseInt`? (Professor is a dumb, he don't know about this funcion). – Miljan Puzović Apr 12 '13 at 19:02
  • You do have to parse it, because a String compare is different than an Integer compare. Since a Sring compares character by character. So `11 < 9` with an String compare. Because 1 is smaller than 9, and than the second number will be compared. – Niels Apr 12 '13 at 19:04
  • Well que sera sera, I'll use parseInt() or Number(). It works fine now. Thanks! – Miljan Puzović Apr 12 '13 at 19:15
  • Yes use `Number()`. See http://stackoverflow.com/questions/4090518/string-to-int-use-parseint-or-number for more info about the difference.     Or multiply it by 1 ('since multiplying assumes numbers, JavaScript makes the string a number, if possible. If that isn't possible, the result is NaN.'), see: http://www.quirksmode.org/js/strings.html – GitaarLAB Apr 12 '13 at 19:16
  • 1
    @Niels I edited to include the radix parameter of `parseInt` that should always be included. – Ian Apr 12 '13 at 19:17
  • Alternatives to `parseInt` include `+`, `~~`, `|0`, `*1`... with `+` being the preferred one for Numbers, and `|0` being the preverred one if you require an int. – John Dvorak Apr 12 '13 at 19:31
1

Try this:

function duzinaNiza() {
    var brClanova = prompt("Enter the number of array elements:");

    if (brClanova > 0) {
        var niz = new Array();

        for (i=0; i<brClanova; i++) {
            var redniBr = i+1;
            niz[i] = parseInt(prompt("Enter "+ redniBr +". array number:"));
            // prompt for geting each array element
        }


        var maximum = niz[0];

        for (a=0; a<brClanova; a++) {

            if (maximum < niz[a]) {
                maximum = niz[a];
            }
        }

        document.write("Greatest value in array is: " + maximum);   
    }
}
Tom
  • 4,422
  • 3
  • 24
  • 36
1

try this out, [Tip: i just utilised the '+' operator for casting the value to number (values from prompt.). The '+' operator will return NaN, if the entered value could not get converted into a number. so in that situation, you should use isNan function to get rid of that.]

  duzinaNiza = function () {
    var brClanova = prompt("Enter the number of array elements:");

    if (brClanova > 0) {
        var niz = new Array();
        var maximum;

        for (i=0; i<brClanova; i++) {
            var temp = +prompt("Enter "+ i+1 +". number:");
            if(i===0) { maximum = temp }
            else { maximum = (temp > maximum)?temp:maximum; }

        }

        alert("Greatest value in array is: " + maximum);   
    }
}
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
1

The problem is that you are comparing two strings, when you wanted to compare two numbers. In other words, the following expression is LEGAL in javascript and evaluates to true:

if('4' > '393939393'){
    //true! string '4' is greater than string '3' (first char of '393939393')
}

What you should do is cast the value received from the function prompt, so it is treated as a number. You can do that using the following function:

parseInt(prompt("Enter "+ redniBr +". array number:"), 10);

The first parameter is the value you want to cast to a number, while the second is the radix (or "base") of the number.

Marlon Bernardes
  • 13,265
  • 7
  • 37
  • 44
1

So, the main problem here is that you're not threat your numbers as "number", but as string. The method prompt returns a string, so you need to convert them:

 function duzinaNiza() {
    var brClanova = +prompt("Enter the number of array elements:");

    if (!brClanova)
      return;

    var niz = [];

    for (var i=0; i < brClanova; i++) {
        var redniBr = i + 1;
        niz[i] = +prompt("Enter "+ redniBr + ". array number:");
    }

    var max = niz[0]; 

    for (var a = 1; a < brClanova; a++) {

      if (max < niz[a])
         max = niz[a];

    }

    document.write("Greatest value in array is: " + max);
}

I used the Unary Plus Operator for that.

Just for to know, in JS you can actually avoid the last loop using Math.max to get the maximum of an array of numbers. So instead of:

    var max = niz[0]; 

    for (var a = 1; a < brClanova; a++) {

      if (max < niz[a])
         max = niz[a];

    }

    document.write("Greatest value in array is: " + max);

You will have:

    var max = Math.max.apply(null, niz);

    document.write("Greatest value in array is: " + max);

In that case, you don't even need the unary plus operator because Math.max takes care of that.

ZER0
  • 24,846
  • 5
  • 51
  • 54
1

You don't need parseInt- if you subtract strings that can be converted to numbers, they are converted. So you can subtract the maximum from the next number, and see if it leaves a remainder.

Also, parseInt will destroy decimals, so you won't know that 1.5 is greater than 1.

Your comment used the wrong characters- `('\' should be '//')

function duzinaNiza(){
    var brClanova= prompt("Enter the number of array elements:");
    if(brClanova>0){
        var niz= new Array();
        for(var i= 0;i<brClanova;i++){
            var redniBr= i+1;
            niz[i]= prompt("Enter "+ redniBr +". array number:");
            //prompt for geting each array element
        }
        var maximum= niz[0];
        for(var a= 0;a<brClanova;a++){
            if(niz[a]-maximum>0){
                maximum= niz[a];
            }
        }
        document.write("Greatest value in array is: " + maximum);
    }
}
kennebec
  • 102,654
  • 32
  • 106
  • 127
  • Thanks. I know about comment characters, I've edited code on-the-fly to paste code here. Original code was without comments and in serbian lanquage :) – Miljan Puzović Apr 12 '13 at 21:52
0

Modified Code JSFIDDLE

function duzinaNiza() {
    var brClanova = prompt("Enter the number of array elements:")*1; //convert string to intger

    if (brClanova > 0) {
        var niz = new Array();

        for (i=0; i<brClanova; i++) {
            var redniBr = i+1;
            niz[i] = prompt("Enter "+ redniBr +". array number:")*1;
            // prompt for geting each array element
        }


        var maximum = niz[0];

        for (a=0; a<brClanova; a++) {

            if (maximum < niz[a]) {
                maximum = niz[a];
            }
        }

        document.write("Greatest value in array is: " + maximum);   
    }
}
Anoop
  • 23,044
  • 10
  • 62
  • 76
  • Multiplying a string by 1 to convert to an integer is not the way to do it – Tom Apr 12 '13 at 19:10
  • @Tom, there are a lot of people would disagree. This has always worked. 'Since multiplying assumes numbers, JavaScript makes the string a number, if possible. If that isn't possible, the result is NaN.' see: http://www.quirksmode.org/js/strings.html – GitaarLAB Apr 12 '13 at 19:14
  • @Tom for one item what would be the difference? I dont think performance should be criteria for not using *1. – Anoop Apr 12 '13 at 19:19
  • Well you will also have some cross browser problems because some browsers don't follow the standard you stated, but all browsers support parseInt. – Tom Apr 12 '13 at 19:20
  • 1
    I know all browser support parseInt. But all browser also support multiplication. I use it frequently and never faced any such problem – Anoop Apr 12 '13 at 19:21
  • @Tom: actually... well look for yourself: http://jsperf.com/convert-string-to-number-techniques/2       Besides, If you'd need to run that instruction just once.. then you've saved 8 bytes! (You'd need a darn good optimizer to catch this one automagically when minifying.) – GitaarLAB Apr 12 '13 at 19:24
  • But treating strings the way most browsers treat them is a standard that some browsers don't follow so it's better just to use parseInt – Tom Apr 12 '13 at 19:29
  • @Tom url shared by GitaarLAB has result for all browsers. Thanks GitaarLAB for sharing link – Anoop Apr 12 '13 at 19:33
  • 1
    My jsperf link was mainly intended to give a weighted overview on speed.     @Tom, you have got me intrigued. Could you *please specify one browser(version)* where this does not work?      I just checked the ES5 standard and there is *specified* that values left and right to the `*` operator in a `MultiplicativeExpression` are automatically passed through `ToNumber` ([ES5 sec 11.5](http://people.mozilla.org/~jorendorff/es5.html#sec-11.5)). So it does also seem to be within spec. – GitaarLAB Apr 12 '13 at 20:29