In this post we will go through the process of adding two numbers in Java.
Problem :
here is the simple example –
Input :
Enter the first number: 10 Enter the second number: 5
Output :
The sum of the two numbers is: 15.
Explanation :
In this example, the user entered 10
as the first number and 5
as the second number. The program then calculated the sum (10 + 5 = 15
) and displayed the result. The actual output will depend on the specific numbers you enter during the program execution.
Solution :
Algorithm for addition of two numbers:
- Declare and initialize two variables you want to add.
- Declare another variable to store the sum of numbers.
- use the “+” operator to add the numbers.
- Display the result.
Approach 1 : Sum of Two Numbers
//Addition of two numbers class SumofNumbers{ public static void main(String[]args){ int num1=40; int num2=20; int sum=num1+num2; System.out.println("Addition of two numbers is :"+sum); } }
Output:
Addition of two numbers is : 60
Approach 2 : Using Scanner Class (User Input)
import java.util.Scanner; class SumofNumbers2{ public static void main(String[]args){ Scanner sc=new Scanner(System.in); System.out.println("Enter the first number"); int n1 =sc.nextInt(); System.out.println("Enter the second number"); int n2 =sc.nextInt(); int sum = n1+n2; System.out.println("the sum of these two numbers is :"+sum); } }
Output :
Enter the first number: 26 Enter the second number: 34 the sum of these two numbers is : 60