Entering 3 Numbers in Prompt and Getting the Max in JavaScript - javascript

I'm new to this. I'm working on exercises for a class and as the subject states I'm trying to have the user enter 3 numbers in the prompt window that appears. This works fine, but I'm trying to get the highest number that was entered to appear after the prompt is over. As I've noted in the code, can anything be added to Math.max to make this work, it's very close to working, but isn't quite there. I appreciate any help.
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Number Input with Prompt
</title>
<script type = "text/javascript">
<!--
var total;
var inputNumber;
var value;
var highestNumber;
var finalMax = Math.max. //<-----Can anything be added here to get the maximum number entered in the prompt window that appears?
total = 0;
inputNumber = 1;
while ( inputNumber <= 3 ){
highestNumber = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
while(isNaN(value = parseInt( highestNumber ))){
highestNumber = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
}
total = total + value;
inputNumber = inputNumber + 1;
}
document.writeln(
"<h1>The highest number is " + finalMax + "</h1>" );
// -->
</script>
</head>
<body>
</body>
</html>

This approach compares the response to an up-to-date highest.
logic = "If value > highestNumber, highestNumber = value"
<script type = "text/javascript">
<!--
var total;
var inputNumber;
var value;
var highestNumber;
//var finalMax = Math.max. //<-----Can anything be added here to get the maximum number entered in the prompt window that appears?
total = 0;
inputNumber = 1;
while ( inputNumber <= 3 ){
value = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
while(isNaN(parseInt( value ))){
value = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
}
if (highestNumber == undefined || highestNumber < value) {
highestNumber = value;
}
total = total + value;
inputNumber = inputNumber + 1;
}
document.writeln(
"<h1>The highest number is " + highestNumber + "</h1>" );
// -->
</script>

A better way to do that would be like this
var nums = new Array();
for(var i=0; i<3; i++){
nums[i] = window.prompt( "Enter number " + (i+1) + " of 3:" , "" );
}
document.writeln("<h1>The highest number is " + Math.max.apply(null, nums) + "</h1>" );

This approach logs all answers and runs the compare at the end, thus making use of Math.max()
logic = "highestNumber = Math.max(first,second,third)"
<script type = "text/javascript">
<!--
var total;
var inputNumber;
var value;
var highestNumber = [];
//var finalMax = Math.max. //<-----Can anything be added here to get the maximum number entered in the prompt window that appears?
total = 0;
inputNumber = 1;
while ( inputNumber <= 3 ){
value = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
while(isNaN(parseInt( value ))){
value = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
}
highestNumber[inputNumber] = value;
total = total + value;
inputNumber = inputNumber + 1;
}
finalMax = Math.max(highestNumber[1], highestNumber[2], highestNumber[3]);
document.writeln(
"<h1>The highest number is " + finalMax + "</h1>" );
// -->
</script>

If you need or want to use Math.max to find your maximum, you should add each valid entry to an array of numbers and call Math.max.apply(null, numbers);
The following fiddle shows this in action: http://jsfiddle.net/T2Gxm/

Related

Finding the factorial using a loop in javascript

I need to use a loop to find the factorial of a given number. Obviously what I have written below will not work because when i = inputNumber the equation will equal 0.
How can I stop i reaching inputNumber?
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 0; i <= inputNumber; i++){
total = total * (inputNumber - i);
}
console.log(inputNumber + '! = ' + total);
here is an error i <= inputNumber
should be i < inputNumber
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 0; i < inputNumber; i++){
total = total * (inputNumber - i);
}
console.log(inputNumber + '! = ' + total);
you can keep this:
i <= inputNumber
and just do this change:
total = total * i;
then the code snippet would look like this:
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 1; i <= inputNumber; ++i){
total = total * i;
}
console.log(inputNumber + '! = ' + total);
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 0; i < inputNumber; i++){
total = total * (inputNumber - i);
}
alert(inputNumber + '! = ' + total);
You could use the input value and a while statement with a prefix decrement operator --.
var inputNumber = +prompt('Please enter an integer'),
value = inputNumber,
total = inputNumber;
while (--value) { // use value for decrement and checking
total *= value; // multiply with value and assign to value
}
console.log(inputNumber + '! = ' + total);
Using total *= i; will set up all of your factorial math without the need of extra code. Also, for proper factorial, you'd want to count down from your input number instead of increasing. This would work nicely:
var inputNum = prompt("please enter and integer");
var total = 1;
for(i = inputNum; i > 1; i--){
total *= i;
}
console.log(total);
function factorialize(num) {
var result = num;
if(num ===0 || num===1){
return 1;
}
while(num > 1){
num--;
result =num*result;
}
return result;
}
factorialize(5);

Cannot get a JavaScript program to add odd numbers

Here's the problem:
Create a sum program that calculates the sum of all odd numbers between 1 and the number entered by the user. For example if the user enters in the number 7 the program would calculate 1 + 3 + 5 + 7. The total and the expression should be displayed on the document. The answer would be 16.
My code so far
//declare the variables
var sternum = prompt("enter a number");
var tantalum = 1;
var increase = 1;
var expression = "+";
//finding the sum
document.write(" the sum of all numbers are: ");
do {
if(sternum % 2 == 0) {
}
else{
document.write(increase + expression);
increase = increase + 1;
tantalum = tantalum + increase;
}
}while(increase < sternum);
document.write(sternum + " = " + tantalum);
You have created an infinite loop. Make sure you increment increase every iteration:
var sternum = prompt("enter a number");
var tantalum = 0;
var increase = 1;
var expression = "+";
//finding the sum
document.write(" the sum of all numbers are: ");
do {
if(increase % 2 == 0) {
}
else{
document.write(increase + expression);
tantalum = tantalum + increase;
}
increase = increase + 1;
}while(increase <= sternum);
document.write(" = " + tantalum);
To make it more efficient you could change increase = increase + 1; to increase = increase + 2;. No need to process even numbers. Also tantalum should be set to 0 to start.

Extra + in output when looping; javascript

My desired output is: 5 + 6 + 7 + 8 + 9 + 10 = 45
The output I'm getting is: 1 + 2 + 3 + 4 + 5 + = 15 (with an extra + side on the end). I'm not sure how to get it to output without the extra + at the end, and am clearly not searching for the right terms to figure it out. Thanks!
Here's my code:
function exercise7Part2() {
// PART 2: YOUR CODE STARTS AFTER THIS LINE
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart + " + ");
loopStart++;
}
document.write(" = " + total);
}
It's because you're printing loopState + "+" which will always print the + at the end. Instead you must check if it's the last value and prevent the + from printing or else, use a ternary operator to print it.
In this example, I'm checking if both loopStart and loopMax are not equal. if they're not equal then am appending + at the end.
It will be like:
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
Here (loopStart!=loopMax ? "+" : "") is a ternary operator. The loopStart!=loopMax is an boolean expression. It's evaluated and if it's true the first parameter after ? will be used so in this case + and if its false anythign after : will be used so in this case its "" empty string.
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
loopStart++;
}
document.write(" = " + total);
With normal if condition block
while (loopStart <= loopMax)
{
total += loopStart;
if(loopStart===loopMax) {
document.write(loopStart);
} else {
document.write(loopStart+ "+");
}
loopStart++;
}
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
loopStart++;
}
document.write(" = " + total);

How to run a continuous loop in javascript

while(userInput!= -1)
{
var total=0.0;
var totalEarnings=0;
var item;
//var userInput;
var salesPerson=1;
var userInput= parseInt(prompt("outsidePlease enter noOfItemsSold of Item# 1 sold for SalesPerson #"+salesPerson+"\n"+" OR -1 to Exit "));
salesPerson++;
//alert("in while "+salesPerson);
//userInput= parseInt(prompt("Please enter noOfItemsSold of Item# "+item+" sold for SalesPerson #"+salesPerson+"\n"+" OR -1 to Exit "));
//if(userInput!=-1)
//{
for(item=2;item<5;item++)
{
//userInput= parseInt(prompt("Please enter noOfItemsSold of Item# "+item+" sold for SalesPerson #"+salesPerson+"\n"+" OR -1 to Exit "));
//var noOfItemsSold = parseInt( userInput);
if ( item == 1 )
{
total += userInput * 239.99;
}
else if (item == 2 )
{
total += userInput * 129.75;
}
else if ( item == 3 )
{
total += userInput * 99.95;
}
else if ( item == 4 )
{
total += userInput * 350.89;
}
var input= parseInt(prompt("Please enter noOfItemsSold of Item# "+item+" sold for SalesPerson #"+salesPerson+"\n"+" OR -1 to Exit "));
}
totalEarnings = .09 * total + 200;
document.writeln( "<h1>SalesPerson#"+salesPerson+" Total Earnings this week is " +totalEarnings +"</h1>" );
}
I am trying to run the continuous loop. Script is calculating the total earnings of salesperson, and I want to run the script till the user enter -1.
I don't know what I am doing wrong but this is not working.
How can I fix this?
while (1) {
if (condition met) {
break;
}
}
your loop will always be true until your conditional test (insert yours is true) and then it will break and go on to the rest of your code.
Basically, the condition isn't evaluated until after the iteration of the loop has completed. So, if the user types in -1, the for loop will still be executed which is probably not what you want.
I suggest using the break; keyword to exit the loop. Trying something like this:
while(true) // Loop forever, since we'll break manually
{
var total = 0.0;
var totalEarnings = 0;
var item;
var salesPerson = 1;
var userInput = parseInt(prompt("outsidePlease enter noOfItemsSold of Item# 1 sold for SalesPerson #"+salesPerson+"\n"+" OR -1 to Exit "));
salesPerson++;
if(userInput == -1) // Exit immediately!
break;
for(item=2;item<5;item++)
{
// ...
}
}
I've cleaned up the code a bit:
var total;
var totalEarnings;
var item;
var salesPerson;
var userInput;
var input;
while ( userInput != -1 ) {
total = 0.0;
totalEarnings = 0;
salesPerson = 1;
userInput = parseInt( prompt( "outsidePlease enter noOfItemsSold of Item# 1 sold for SalesPerson #" + salesPerson + "\n OR -1 to Exit" ), 10 );
salesPerson++;
for ( item = 2; item < 5; item++ ) {
if ( item == 1 ) {
total += userInput * 239.99;
} else if (item == 2 ) {
total += userInput * 129.75;
} else if ( item == 3 ) {
total += userInput * 99.95;
} else if ( item == 4 ) {
total += userInput * 350.89;
}
input = parseInt( prompt( "Please enter noOfItemsSold of Item# " + item + " sold for SalesPerson #" + salesPerson + "\n OR -1 to Exit" ) );
}
totalEarnings = .09 * total + 200;
document.writeln( "<h1>SalesPerson#" + salesPerson + " Total Earnings this week is " + totalEarnings + "</h1>" );
}
Your loop will repeat as long as userInput has a value other than -1.
Now let's look at what each iteration of the loop does:
It assigns some initial values to a few variables.
It prompts the user to input a value; that value is assigned to userInput.
It then (rather bizarrely) repeats a similar prompt to the user, this time assigning them to input (not userInput) and using them to perform calculations for total.
The only time userInput is ever assigned a value is in step 2:
userInput = parseInt( prompt( "outsidePlease enter noOfItemsSold of Item# 1 sold for SalesPerson #" + salesPerson + "\n OR -1 to Exit" ), 10 );
And if you enter -1 as your input here, the loop will terminate, just as expected.

If Statement? Don't add numbers into total variable if they are negative

Question, how do I make it so when an user-inputted number is negative, it isn't added to the total variable that will be ouput?
Code below!
function lab10logicInLoopsPart1()
{
lCounter = 1;
var total = 0;
userNumber = 0;
while(lCounter < 6) {
lCounter++;
userNumber = prompt("Enter a number.");
total += +userNumber;
document.write("Entered number was: " + userNumber + "\n");
}
document.write("\nTotal: " + total);
}
After prompting the user to enter a number, just check it's not a negative with an if statement:
if(userNumber >=0)
{ //do your stuff here}

Categories

Resources