Infolinks

Breaking

Adsense

Friday, April 22, 2016

CREATE A PROGRAM TO ADD INTEGERS USING A WINDOW PROMPT IN JAVASCRIPT

The following javascript code inputs two (2) integers (whole numbers, such as 100, 2, 55) and solve for the sum of the two numbers and display the results.

The script uses a dialog box called the prompt dialog box that allows a user to input a value to be used in the script. The result will be displayed using the document.writeln.

JAVASCRIPT CODE TO ADD TWO INTEGERS

<html>
<head>
<script>
var first,second,firstnum,secondnum,sum;
first=window.prompt("Enter the first number:", "0");
second=window.prompt("Enter the second number:", "0");

firstnum=parseInt(first);
secondnum=parseInt(second);

sum=firstnum+secondnum;
document.writeln("The sum of "+firstnum +" and "+secondnum+ " is "+sum);
</script>
</head>
</html>

I will explain the script briefly for you to understand each line well. In javascript, you need to declare all variables before you can use them. var first,second,firstnum,secondnum,sum; is your variable declaration.

first=window.prompt("Enter the first number:", "0");
second=window.prompt("Enter the second number:", "0"); this two lines of code is responsible in displaying a dialog box in which a user can input two numbers that will be used in calculation later.

firstnum=parseInt(first);             
secondnum=parseInt(second);
The code above will convert the numbers inputted by the user into integer since the default data type from inputs is string. So to be able to used arithmetic operators such as addition, you need to convert it into number data type first. In our case, we converted it into integer data type.

sum=firstnum+secondnum;
This is your formula to solve for the sum of the first and second number.

And the last line,
document.writeln("The sum of "+firstnum +" and "+secondnum+ " is "+sum);
will display the inputted numbers together with their sum. The plus sign (+) there serves as a concatenation operator between strings and variable values. Concatenation means combining two or more string or values.   Always remember to enclose your string values with a double quotation.
Hope this helps! ^_^


SAMPLE OUTPUT THAT ADDS TWO INTEGERS IN JAVASCRIPT





CREATE A PROGRAM TO ADD INTEGERS USING A WINDOW PROMPT IN JAVASCRIPT

No comments:

Post a Comment

Adbox