Sebesta Ch 4 Problems Problem 4.3 Version 0 - no loops // Start with 'raw code' - no functions. // Test that we can use prompt by echoing input. ALWAYS // echo input when testing. First solution. Find a test case for which this does not work. Now, a working version. Package this code in a function. Note that our text says that function definitions must come before the function is called. Some browsers may require this, but I have never encountered it. *********************************************************** Here is a solution to problem 4.3 using arrays *********************************************************** // Unlike Java, displaying an array shows all the values // without the need for a loop. // Version 1 - array and loop function prob43v1() { var values = new Array(3); for(var index=0; index < 3; index++) { values[index] = Number(prompt('enter number','')); } alert('values = ' + values); } Here is a really irritating feature of JS. This code executes without complaint. What is wrong with it? // Version 1 - array and loop function prob43v1() { var values = new Array(3); for(var index=0; index < 3; index++) { values[index] = Number(prompt('enter number','')); } var max = values[0]; for(var index = 1; index < 3; index++) if(value[index] > max) max = value[index]; alsert('max = ' + max); } A corrected version works. // Version 1 - array and loop function prob43v1() { var values = new Array(3); for(var index=0; index < 3; index++) { values[index] = Number(prompt('enter number','')); } var max = values[0]; for(var index = 1; index < 3; index++) if(values[index] > max) max = values[index]; alert('max = ' + max); } Refactor this code to eliminate the magic number. // Version 1 - array and loop function prob43v1() { var SIZE = 3; var values = new Array(SIZE); for(var index=0; index < SIZE; index++) { values[index] = Number(prompt('enter number','')); } var max = values[0]; for(var index = 1; index < SIZE; index++) if(values[index] > max) max = values[index]; alert('max = ' + max); } // Version 2 - Math.max function prob43v2() { var SIZE = 3; var values = new Array(SIZE); for(var index=0; index < SIZE; index++) { values[index] = Number(prompt('enter number','')); } var max = Math.max(values[0],Math.max(values[1],values[2])); alert('max = ' + max); } // Version 2a - Math.max - no array function prob43v2a() { var SIZE = 3; var max = -999999999; for(var index=0; index < SIZE; index++) { max = Math.max(max,Number(prompt('enter number',''))); } alert('max = ' + max); }