Arithmetic Operators – Computer Sir Ki Class Code Learning #JAVA#3657    ## Arithmetic Operators

Addition, subtraction, multiplication, division and modulus operator

## Learning Objectives

• Understanding the simple use of arithmetic operators

## Source Code

 class ArithmeticOp { public static void main(String[] args) { int a=10; int b=4; int c=a+b; int d=a-b; int e=a*b; int f=a/b; int g=a%b; System.out.println("a = "+a+" b = "+b); System.out.println("a+b = "+c); System.out.println("a-b = "+d); System.out.println("a*b = "+e); System.out.println("a/b = "+f+" (Integer Division)"); System.out.println("a%b = "+g); } } .linedwrap { border: 1px solid #c0c0c0; padding-top: 5px; padding-bottom: 5px; border-radius: 4px; background-color:#F8F8F8; } .linedtextarea { padding: 0px; margin: 0px; background-color:#F8F8F8; } .linedtextarea textarea, .linedwrap .codelines .lineno { font-size: 12pt; font-family: monospace; line-height: normal !important; } .linedtextarea textarea { padding-right:0.3em; padding-top:0.3em; border: 0; } .linedwrap .lines { margin-top: 0px; width: 20px; float: left; overflow: hidden; border-right: 1px solid #c0c0c0; margin-right: 10px; } .linedwrap .codelines { padding-top: 5px; } .linedwrap .codelines .lineno { color:#AAAAAA; padding-right: 2px; padding-top: 0.0em; text-align: right; white-space: nowrap; } .linedwrap .codelines .lineselect { color: red; }

## Run Output

``````a = 10 b = 4
a+b = 14
a-b = 6
a*b = 40
a/b = 2 (Integer Division)
a%b = 2
``````

## Code Understanding

int a=10; int b=4;
Integer variables a and b have been initialised here

int d=a-b; //subtraction operator
int e=a*b; //multiplication operator
int f=a/b; //Division Operator
int g=a%b; //Modulus operator to get the remainder after division

System.out.println(“a = “+a+” b = “+b);
System.out.println(“a+b = “+c);
System.out.println(“a-b = “+d);
System.out.println(“a*b = “+e);
System.out.println(“a/b = “+f+” (Integer Division)”);
System.out.println(“a%b = “+g);
Operator based results are printed above.

## Common Errors

• One may often forget that in the integer form 10/4 would be 2 and not 2.5 as the fractional portion would be ignored while storing in integer form. If we use double or float form, 10/4 will have to be written as 10.0/4 and stored as double or float, then it would be 2.5.

Suggested Filename(s): ArithmeticOp.java

sunmitra| Created: 1-Mar-2018 | Updated: 1-Mar-2018|

×