Addition of two numbers in java

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:

  1.  Declare and initialize two variables you want to add.
  2.  Declare another variable to store the sum of numbers.
  3.  use the “+” operator to add the numbers.
  4.  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
Basic Java Program :

Leave a Comment

%d bloggers like this:
Python4U
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.