Computer Science, asked by sona1640, 1 year ago

Wap in java to find sum difference product and division of two numbers​

Answers

Answered by 15121115anil
5

import java.util.Scanner;

public class JavaProgram

{

public static void main(String args[])

{

int a, b, res;

Scanner scan = new Scanner(System.in);

System.out.print("Enter Two Numbers : ");

a = scan.nextInt();

b = scan.nextInt();

res = a + b;

System.out.println("Addition = " +res);

res = a - b;

System.out.println("Subtraction = " +res);

res = a * b;

System.out.println("Multiplication = " +res);

res = a / b;

System.out.println("Division = " +res);

}

}

Answered by QGP
3

Arithmetic Operations - Java

We have to write a simple Java program showing the four arithmetic operations: sum, difference, product and division.

We start by using the Scanner class to take user input for the two numbers. We store the numbers as double data type, which will help maintaining precision in division. [Integer data type will not give an intended answer for the division operator. Also, it won't allow fractional number input.]

After that, we calculate the required quantities by performing the arithmetic operations using the +, -, * and / operators.

Division by 0 is Invalid. So, we add an if-else block to check if the second number is 0 or not. If it is not 0, we proceed with the division. Else, we display an error message.

Here's the code of the program:

 \rule{320}{1}

import java.util.Scanner;   //Importing Scanner

public class ArithmeticOperations    //Creating Class

{

   public static void main(String[] args)      //Creating the main method

   {

       Scanner sc = new Scanner(System.in);    //Creating the Scanner object

       //Take User Inputs for two numbers. Store as "double" type.

       System.out.print("Enter the first number: ");  

       double num1 = sc.nextDouble();

       System.out.print("Enter the second number: ");

       double num2 = sc.nextDouble();

       double sum = num1 + num2;       //Calculating Sum

       System.out.println(num1+" + "+num2+" = "+sum);  

       double difference = num1 - num2;    //Calculating Difference

       System.out.println(num1+" - "+num2+" = "+difference);

       

       double product = num1 * num2; //Calculating Product

       System.out.println(num1+" * "+num2+" = "+product);

       //Division by 0 is not possible.  

       //So we first check if num2 is 0 or not

       if(num2 != 0)       //num2 is not equal to 0

       {

           double division = num1 / num2;  //Calculating Division

           System.out.println(num1+" / "+num2+" = "+division);

       }

       else    //Condition of division by 0, which is invalid

       {

           System.out.println("Division by 0 is Invalid.");

       }

   }

}

Attachments:
Similar questions