Course: JavaScript

Progress (0%)

  1. Foundation

  2. Numbers

  3. Strings

  4. Conditions

  5. Loops

  6. Arrays

  7. Functions

  8. Objects

  9. Exceptions

  10. HTML DOM

  11. CSSOM

  12. Events

  13. Drag and Drop

  14. opt Touch Events

  15. Misc

  16. Project: Analog Clock

Exercise: Addition Calculator

Exercise 1 Very easy

Prerequisites for the exercise

  1. JavaScript Basics

Objective

Create a program that takes in two integers and outputs their sum onto the HTML document.

Description

In this exercise, you have to create a program that asks the user to input two integers, one-by-one, and then outputs their sum.

Each of these inputs is to be obtained using a prompt dialog.

The first input prompt should display the following text: 'a = ?'. The second input prompt should display 'b = ?'

The output should be as follows:

The sum is: <sum>

where <sum> is the sum of the input integers.

In the actual output, you have to show the sum of the input values in place of <sum>. The reason to use <sum> is just to give the general form of the output.

Shown below is an example:

Live Example

View Solution

New file

Inside the directory you created for this course on JavaScript, create a new folder called Exercise-1-Addition-Calculator and put the .html solution files for this exercise within it.

Solution

As instructed in the exercise, we first need to set up the input prompts.

This is accomplished below:

var a = prompt('a = ?');
var b = prompt('b = ?');

The value input in the first prompt gets saved in the variable a while the input in the second prompt gets saved in the variable b.

Next, we need to convert both these variables into a number. This is necessary because we have to add the input values together, which requires them to be in numeric format.

var a = prompt('a = ?');
var b = prompt('b = ?');

a = Number(a);
b = Number(b);

With the values converted into equivalent numbers, it's time to add these numbers together:

var a = prompt('a = ?');
var b = prompt('b = ?');

a = Number(a);
b = Number(b);

var sum = a + b;

Finally, we are left to just make the desired output:

var a = prompt('a = ?');
var b = prompt('b = ?');

a = Number(a);
b = Number(b);

var sum = a + b;

document.write('The sum is: ' + sum);

Live Example