TypeScript – Arithmetic Operators Examples

In this topic, we will discuss Arithmetic Operators Examples in Typescript.

Assume the values in variables a and b are 10 and 5 respectively.

OperatorDescriptionExample
+ (Addition)returns the sum of the operandsa + b is 15
– (Subtraction)returns the difference of the valuesa – b is 5
* (Multiplication)returns the product of the valuesa * b is 50
/ (Division)performs a division operation and returns the quotienta / b is 2
% (Modulus)performs a division and returns the remaindera % b is 0
++ (Increment)Increments the value of the variable by onea++ is 11
— (Decrement)Decrements the value of the variable by onea– is 9

Example

var num1:number = 10 
var num2:number = 2
var res:number = 0
 
res = num1 + num2 
console.log("Sum:        "+res); 

res = num1 - num2; 
console.log("Difference: "+res) 

res = num1*num2 
console.log("Product:    "+res) 

res = num1/num2 
console.log("Quotient:   "+res)
 
res = num1%num2 
console.log("Remainder:   "+res) 

num1++ 
console.log("Value of num1 after increment "+num1) 

num2-- 
console.log("Value of num2 after decrement "+num2)

On compiling, it will generate following JavaScript code.

//Generated by typescript 1.8.10
var num1 = 10;
var num2 = 2;
var res = 0;

res = num1 + num2;
console.log("Sum:        " + res);

res = num1 - num2;
console.log("Difference: " + res);

res = num1 * num2;
console.log("Product:    " + res);

res = num1 / num2;
console.log("Quotient:   " + res);

res = num1 % num2;
console.log("Remainder:   " + res);

num1++;
console.log("Value of num1 after increment " + num1);

num2--;
console.log("Value of num2 after decrement " + num2);

The output of the above program is given below −

Sum: 12 
Difference: 8 
Product: 20 
Quotient : 5 
Remainder: 0 
Value of num1 after increment: 11 
Value of num2 after decrement: 1

Previous Page:-Click Here

Leave a Reply