In today’s task, you will create a program that performs a simple mathematical operation: adding two numbers and printing the result. This exercise will introduce you to basic arithmetic and how to handle variables in your code.
Performing mathematical operations is a fundamental aspect of programming, as most real-world applications rely on calculations in some form, whether it’s for handling user data, processing financial figures, or manipulating other types of information.
Python: Use the input()
function to get user input. By default, input()
returns data as a string, so you’ll need to convert it to an integer using the int()
function.
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
Java: Use the Scanner
class to take input. The nextInt()
method will help you capture the numbers as integers.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
int sum = num1 + num2;
System.out.println("The sum is: " + sum);
}
}
JavaScript: Use prompt()
to gather user input, and convert the input to numbers using parseInt()
or parseFloat()
(if working with decimals).
let num1 = parseInt(prompt("Enter the first number: "));
let num2 = parseInt(prompt("Enter the second number: "));
let sum = num1 + num2;
console.log("The sum is: " + sum);
After you have stored the user input in variables, simply add the two variables together. The result will be stored in a new variable.
Example (Python):
result = num1 + num2
print("The sum is:", result)
Example (Java):
int sum = num1 + num2;
System.out.println("The sum is: " + sum);
Example (JavaScript):
let sum = num1 + num2;
console.log("The sum is: " + sum);
float()
(Python), nextFloat()
(Java), or parseFloat()
(JavaScript) instead of int()
or nextInt()
.Once you’ve successfully written the program, try extending it. For example, you can:
This exercise is just the beginning. Keep practicing basic operations and experiment with different kinds of input to gain more comfort with coding.