Course: JavaScript

Progress (0%)

Exercise 1 Very easy

Prerequisites for the exercise

## 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:

## 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);``````

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage