Infolinks

Breaking

Adsense

Friday, April 22, 2016

COMPARE TWO INTEGERS USING A WINDOW PROMPT IN JAVASCRIPT

Hi there! I have here another article for you guys that use another control structures using a conditional statement together with relational and equality operators to compare the two values being inputted by a user. This script will identify what decisions to take or what program to be executed based on a certain condition. If the condition is met, then the code after that if statement will be executed. Otherwise, it will skip the code and jump into the next if statement/condition.

JAVASCRIPT CODE TO COMPARE 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);

if (firstnum > secondnum)
document.writeln(firstnum +" > "+secondnum);
if (firstnum == secondnum)
document.writeln(firstnum +" == "+secondnum);
if (firstnum < secondnum)
document.writeln(firstnum +" < "+secondnum);
</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 comparing 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 comparison operators such as greater than, equal, less than, you need to convert it into number data type first. In our case, we converted it into integer data type.

if (firstnum > secondnum)
                document.writeln(firstnum +" > "+secondnum);
if (firstnum == secondnum)
                document.writeln(firstnum +" == "+secondnum);
if (firstnum < secondnum)
                document.writeln(firstnum +" < "+secondnum);

These lines of code is used to decide what to display. Is the first number greater than the other? Or is it lesser? Or perhaps they are equal? Whatever conditions met will decide which code is going to be executed. So our first condition is if (firstnum > secondnum) . If the value of firstnum is 2 and secondnum is 5, then the condition will yield to be true, therefore executing the code after that statement which is to display 2 > 5. Once false, it will skip the code after the if statement and proceed with the next conditional statement.

SAMPLE OUTPUT THAT COMPARES TWO INTEGERS USING A WINDOW PROMPT IN JAVASCRIPT





Hope it helps! Good day! ^_^

COMPARE TWO INTEGERS USING A WINDOW PROMPT IN JAVASCRIPT

No comments:

Post a Comment

Adbox