Arithmetic/Integer: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 249: Line 249:


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>def arithmetic = { a, b ->
println """
a + b = ${a} + ${b} = ${a + b}
a - b = ${a} - ${b} = ${a - b}
a * b = ${a} * ${b} = ${a * b}
a / b = ${a} / ${b} = ${a / b} !!!
(int)(a / b) = (int)(${a} / ${b}) = ${(int)(a / b)} !!!
a % b = ${a} % ${b} = ${a % b}


Exponentiation is also a base arithmetic operation in Groovy, so:
a ** b = ${a} ** ${b} = ${a ** b}
"""
}</lang>

Program:
<lang groovy>arithmetic(5,3)</lang>

Output:
<pre>a + b = 5 + 3 = 8
a - b = 5 - 3 = 2
a * b = 5 * 3 = 15
a / b = 5 / 3 = 1.6666666667 !!!
(int)(a / b) = (int)(5 / 3) = 1 !!!
a % b = 5 % 3 = 2

Exponentiation is also a base arithmetic operation in Groovy, so:
a ** b = 5 ** 3 = 125</pre>


=={{header|Haskell}}==
=={{header|Haskell}}==

Revision as of 19:37, 12 May 2009

Task
Arithmetic/Integer
You are encouraged to solve this task according to the task description, using any language you may know.

Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.

You may see other such operations in the Basic Data Operations category, or:

Integer Operations
Arithmetic | Comparison

Boolean Operations
Bitwise | Logical

String Operations
Concatenation | Interpolation | Comparison | Matching

Memory Operations
Pointers & references | Addresses

Get two integers from the user, and then output the sum, difference, product, integer quotient and remainder of those numbers. Don't include error handling. For quotient, indicate how it truncates (e.g. towards 0, towards negative infinity, etc.). For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.

Ada

<lang ada>with Ada.Text_Io; with Ada.Integer_Text_IO;

procedure Integer_Arithmetic is

  use Ada.Text_IO;
  use Ada.Integer_Text_Io;
  A, B : Integer;

begin

  Get(A);
  Get(B);
  Put_Line("a+b = " & Integer'Image(A + B));
  Put_Line("a-b = " & Integer'Image(A - B));
  Put_Line("a*b = " & Integer'Image(A * B));
  Put_Line("a/b = " & Integer'Image(A / B) & ", remainder " & Integer'Image(A mod B));  

end Integer_Arithmetic;</lang>

ALGOL 68

main:(
  LONG INT a=355, b=113;
  printf(($"a+b = "gl$, a + b));
  printf(($"a-b = "gl$, a - b));
  printf(($"a*b = a×b = "gl$, a * b));
  printf(($"a/b = "gl$, a / b));
  printf(($"a OVER b = a%b = a÷b = "gl$, a % b));
  printf(($"a MOD b = a%*b = a%×b = a÷×b = a÷*b = "gl$, a %* b));
  printf(($"a UP b = a**b = a↑b = "gl$, a ** b))
)

Output:

a+b =                                 +468

a-b = +242 a*b = a×b = +40115 a/b = +3.141592920353982300884955752e +0 a OVER b = a%b = a÷b = +3 a MOD b = a%*b = a%×b = a÷×b = a÷*b = +16

a UP b = a**b = a↑b = +1.499007808785573768814747570e+288

ALGOL 68R has the curious (and consequently non-standard) /:= operator. This operator delivers two INTs as a result. eg.

INT quotient:=355, remainder;
remainder := quotient /:= 113;

Giving a quotient of 3, and a remainder of 16.

AWK

/[0-9]* [0-9]*/{ print ($1 + $2)
		print ($1 - $2)
		print ($1 * $2)
		print int($1 / $2)
		print ($1 % $2)
		exit}

Befunge

 &&00p"=A",,:."=B ",,,00g.55+,v
         v,+55.+g00:,,,,"A+B="<
         >"=B-A",,,,:00g-.55+,v
         v,+55.*g00:,,,,"A*B="<
         >"=B/A",,,,:00g/.55+,v
          @,+55.%g00,,,,"A%B="<


C

<lang c>#include <stdio.h>

  1. include <stdlib.h>

int main(int argc, char *argv[]) {

 int a, b;
 if (argc < 3) exit(1);
 b = atoi(argv[--argc]);
 if (b == 0) exit(2);
 a = atoi(argv[--argc]);
 printf("a+b = %d\n", a+b);
 printf("a-b = %d\n", a-b);
 printf("a*b = %d\n", a*b);
 printf("a/b = %d\n", a/b); /* truncates towards 0 (in C99) */
 printf("a%%b = %d\n", a%b); /* same sign as first operand (in C99) */
 return 0;

}</lang>

C++

<lang cpp>#include <iostream>

int main() {

 int a, b;
 std::cin >> a >> b;
 std::cout << "a+b = " << a+b << "\n";
 std::cout << "a-b = " << a-b << "\n";
 std::cout << "a*b = " << a*b << "\n";
 std::cout << "a/b = " << a/b << ", remainder " << a%b << "\n";
 return 0;

}</lang>

C#

<lang csharp>using System;

class Program {

  static void Main(string[] args)
  {
     if (args.Length < 2)
        return;
      int a = Convert.ToInt32(args[0]);
      int b = Convert.ToInt32(args[1]);
      Console.WriteLine("a - b = {0}", a - b);
      Console.WriteLine("a * b = {0}", a * b);
      if (b != 0) 
      {
         Console.WriteLine("a / b = {0}", a / b);
         Console.WriteLine("a % b = {0}", a % b);
      }
  }

}</lang>

Common Lisp

<lang lisp>(defun arithmetic ()

 (let ((a (read *query-io*)) (b (read *query-io*)))
   (format t "a + b = ~a~%" (+ a b))
   (format t "a - b = ~a~%" (- a b))
   (format t "a * b = ~a~%" (* a b))
   (format t "a / b = ~a~%" (/ a b))
   (format t "a % b = ~a~%" (mod a b))))</lang>

D

<lang d>import std.stdio, std.string;

void main() {

 auto a = readln().atoi(), b = readln().atoi();
 writefln("a + b = ", a+b);
 writefln("a - b = ", a-b);
 writefln("a * b = ", a*b);
 writefln("a / b = ", a/b);
 writefln("a % b = ", a%b);

}</lang>

DOS Batch File

@set /P A=Enter 1st Number :
@set /P B=Enter 2nd Number :
@set D=%A% + %B% & call :printC
@set D=%A% - %B% & call :printC
@set D=%A% * %B% & call :printC
@set D=%A% / %B% & call :printC
@set D=%A% %% %B% 
:printC
@set /A C=%D%
@echo %D% = %C%

E

def arithmetic(a :int, b :int) {
  return `$\
   Sum:        ${a + b}
   Difference: ${a - b}
   Product:    ${a * b}
   Quotient:   ${a // b}
   Remainder:  ${a % b}$\n`
}

Factor

 USING: combinators io kernel math math.functions math.order
 math.parser prettyprint ;
 
 "a=" "b=" [ write readln string>number ] bi@
 {
     [ + "sum: " write . ]
     [ - "difference: " write . ] 
     [ * "product: " write . ]
     [ / "quotient: " write . ]
     [ /i "integer quotient: " write . ]
     [ rem "remainder: " write . ]
     [ mod "modulo: " write . ]
     [ max "maximum: " write . ]
     [ min "minimum: " write . ]
     [ gcd "gcd: " write . drop ]
     [ lcm "lcm: " write . ]
 } 2cleave

output:

 a=8
 b=12
 sum: 20
 difference: -4
 product: 96
 quotient: 2/3
 integer quotient: 0
 remainder: 8
 modulo: 8
 maximum: 12
 minimum: 8
 gcd: 4
 lcm: 24

This example illustrates the use of cleave and apply combinators to alleviate the usage of shuffle words in a concatenative language. bi@ applies a quotation to 2 inputs and 2cleave applies a sequence of quotations to 2 inputs.

FALSE

12 7
\$@$@$@$@$@$@$@$@$@$@\  { 6 copies }
"sum = "+."
difference = "-."
product = "*."
quotient = "/."
modulus = "/*-."
" 

Forth

To keep the example simple, the word takes the two numbers from the stack. /mod returns two results; the stack effect is ( a b -- a%b a/b ).

: arithmetic ( a b -- )
  cr ." a=" over . ." b=" dup .
  cr ." a+b=" 2dup + .
  cr ." a-b=" 2dup - .
  cr ." a*b=" 2dup * .
  cr ." a/b=" /mod .
  cr ." a mod b = " . cr ;

Different host systems have different native signed division behavior. ANS Forth defines two primitive double-precision signed division operations, from which the implementation may choose the most natural to implement the basic divide operations ( / , /mod , mod , */ ). This is partly due to differing specifications in the two previous standards, Forth-79 and Forth-83.

FM/MOD ( d n -- mod div )   \ floored
SM/REM ( d n -- rem div )   \ symmetric
M* ( n n -- d )

In addition, there are unsigned variants.

UM/MOD ( ud u -- umod udiv )
UM* ( u u -- ud )

Fortran

In ANSI FORTRAN 77 or later:

     INTEGER A, B
     PRINT *, 'Type in two integer numbers separated by white space',
    +         ' and press ENTER'
     READ *, A, B
     PRINT *, '   A + B = ', (A + B)
     PRINT *, '   A - B = ', (A - B)
     PRINT *, '   A * B = ', (A * B)
     PRINT *, '   A / B = ', (A / B)
     PRINT *, 'MOD(A,B) = ', MOD(A,B)
     PRINT *
     PRINT *, 'Even though you did not ask, ',
    +         'exponentiation is an intrinsic op in Fortran, so...'
     PRINT *, '  A ** B = ', (A ** B)
     END

Groovy

<lang groovy>def arithmetic = { a, b ->

   println """

a + b = ${a} + ${b} = ${a + b} a - b = ${a} - ${b} = ${a - b} a * b = ${a} * ${b} = ${a * b} a / b = ${a} / ${b} = ${a / b}  !!! (int)(a / b) = (int)(${a} / ${b}) = ${(int)(a / b)}  !!! a % b = ${a} % ${b} = ${a % b}

Exponentiation is also a base arithmetic operation in Groovy, so: a ** b = ${a} ** ${b} = ${a ** b} """ }</lang>

Program: <lang groovy>arithmetic(5,3)</lang>

Output:

a + b = 5 + 3 = 8
a - b = 5 - 3 = 2
a * b = 5 * 3 = 15
a / b = 5 / 3 = 1.6666666667   !!!
(int)(a / b) = (int)(5 / 3) = 1   !!!
a % b = 5 % 3 = 2

Exponentiation is also a base arithmetic operation in Groovy, so:
a ** b = 5 ** 3 = 125

Haskell

main = do
  a <- readLn :: IO Integer
  b <- readLn :: IO Integer
  putStrLn $ "a + b = " ++ show (a + b)
  putStrLn $ "a - b = " ++ show (a - b)
  putStrLn $ "a * b = " ++ show (a * b)
  putStrLn $ "a `div` b = "  ++ show (a `div` b)  -- truncates towards negative infinity
  putStrLn $ "a `mod` b = "  ++ show (a `mod` b)  -- same sign as second operand
  putStrLn $ "a `quot` b = " ++ show (a `quot` b) -- truncates towards 0
  putStrLn $ "a `rem` b = "  ++ show (a `rem` b)  -- same sign as first operand

J

bia     =: title"_ combine calc
calc    =: + , - , * , <.@% , |
combine =: [ ,. ":@|:@,:@]
title   =: >;.2 'Sum: Difference: Product: Quotient: Remainder: '

Note that the verb calc produces all the processing specified for this problem, and that its output is of numeric type. Since other examples here provide textual output, bia produces like results.

Java

<lang java>import java.util.Scanner;

public static void main(String[] args){

 Scanner sc = new Scanner(System.in);
 int a = sc.nextInt();
 int b = sc.nextInt();
 
 int sum = a + b;//integer addition is discouraged in print statements due to confusion with String concatenation
 System.out.println("a + b = " + sum);
 System.out.println("a - b = " + (a - b));
 System.out.println("a * b = " + (a * b));
 System.out.println("quotient of a / b = " + (a / b)); // truncates towards 0
 System.out.println("remainder of a / b = " + (a % b)); // same sign as first operand

}</lang>

to operate :a :b
  (print [a =] :a)
  (print [b =] :b)
  (print [a + b =] :a + :b)
  (print [a - b =] :a - :b)
  (print [a * b =] :a * :b)
  (print [a / b =] int :a / :b)
  (print [a mod b =] modulo :a :b)
end

Each infix operator also has a prefix synonym (sum, difference, product, quotient). Sum and product can also have arity greater than two when used in parentheses (sum 1 2 3). Infix operators in general have high precedence; you may need to enclose their arguments in parentheses to obtain the correct expression.

LSE64

over : 2 pick
2dup : over over

arithmetic : \
  " A=" ,t over , sp " B=" ,t dup , nl \
  " A+B=" ,t 2dup + , nl \
  " A-B=" ,t 2dup - , nl \
  " A*B=" ,t 2dup * , nl \
  " A/B=" ,t 2dup / , nl \
  " A%B=" ,t      % , nl

M4

Because of the particular nature of M4, the only user-input is the code itself. Anyway the following code can be used: <lang m4>eval(A+B) eval(A-B) eval(A*B) eval(A/B) eval(A%B)</lang>

once saved in a file, e.g. operations.m4:

m4 -DA=4 -DB=6 operations.m4

or using a sort of driver:

<lang m4>define(`A', 4)dnl define(`B', 6)dnl include(`operations.m4')</lang>


MAXScript

x = getKBValue prompt:"First number"
y = getKBValue prompt:"Second number:"

format "Sum: %\n" (x + y) 
format "Difference: %\n" (x - y) 
format "Product: %\n" (x * y) 
format "Quotient: %\n" (x / y) 
format "Remainder: %\n" (mod x y) 

Metafont

<lang metafont>string s[]; message "input number a: "; s1 := readstring; message "input number b: "; s2 := readstring; a := scantokens s1; b := scantokens s2;

def outp(expr op) =

 message "a " & op & " b = " & decimal(a scantokens(op) b) enddef;

outp("+"); outp("-"); outp("*"); outp("div"); outp("mod");

end</lang>

Modula-3

<lang modula3>MODULE Arith EXPORTS Main;

IMPORT IO, Fmt;

VAR a, b: INTEGER;

BEGIN

 a := IO.GetInt();
 b := IO.GetInt();
 IO.Put("a+b = " & Fmt.Int(a + b) & "\n");
 IO.Put("a-b = " & Fmt.Int(a - b) & "\n");
 IO.Put("a*b = " & Fmt.Int(a * b) & "\n");
 IO.Put("a DIV b = " & Fmt.Int(a DIV b) & "\n");
 IO.Put("a MOD b = " & Fmt.Int(a MOD b) & "\n");

END Arith.</lang>

OCaml

<lang ocaml>let _ =

 let a = read_int ()
 and b = read_int () in
 Printf.printf "a + b = %d\n" (a + b);
 Printf.printf "a - b = %d\n" (a - b);
 Printf.printf "a * b = %d\n" (a * b);
 Printf.printf "a / b = %d\n" (a / b);    (* truncates towards 0 *)
 Printf.printf "a mod b = %d\n" (a mod b) (* same sign as first operand *)</lang>

Pascal

program arithmetic(input, output)

var
 a, b: integer;

begin
 readln(a, b);
 writeln('a+b = ', a+b);
 writeln('a-b = ', a-b);
 writeln('a*b = ', a*b);
 writeln('a/b = ', a div b, ', remainder ", a mod b);
end.

Perl

Works with: Perl version 5.x

<lang perl>my $a = <>; my $b = <>;

print

   "sum:              ", $a + $b, "\n",
   "difference:       ", $a - $b, "\n",
   "product:          ", $a * $b, "\n",
   "integer quotient: ", int($a / $b), "\n",
   "remainder:        ", $a % $b, "\n"
   ;</lang>

Pop11

;;; Setup token reader
vars itemrep;
incharitem(charin) -> itemrep;
;;; read the numbers
lvars a = itemrep(), b = itemrep();
;;; Print results
printf(a + b, 'a + b = %p\n');
printf(a - b, 'a - b = %p\n');
printf(a * b, 'a * b = %p\n');
printf(a div b, 'a div b = %p\n');
printf(a mod b, 'a mod b = %p\n');

Python

<lang python>x = int(raw_input("Number 1: ")) y = int(raw_input("Number 2: "))

print "Sum: %d" % (x + y) print "Difference: %d" % (x - y) print "Product: %d" % (x * y) print "Quotient: %d" % (x / y) # or x // y for newer python versions.

                                  # truncates towards negative infinity

print "Remainder: %d" % (x % y) # same sign as second operand

    1. Only used to keep the display up when the program ends

raw_input( )</lang>

Notes: In Python3 raw_input() will be renamed to input() (the old input() built-in will go away, though one could use eval(input()) to emulate the old ... and ill-advised ... behavior). Also a better program would wrap the attempted int() conversions in a try: ... except ValueError:... construct such as:

<lang python> def getnum(prompt):

   while True: # retrying ...
       try:
           n = int(raw_input(prompt))
       except ValueError:
           print "Input could not be parsed as an integer. Please try again."\
           continue
       break
   return n

x = getnum("Number1: ") y = getnum("Number2: ") ... </lang>

(In general it's good practice to perform parsing of all input in exception handling blocks. This is especially true of interactive user input, but also applies to data read from configuration and other files, and marshaled from other processes via any IPC mechanism).

Python also has the procedure divmod that returns both quotient and remainder. eg

quotient, remainder = divmod(355,113)

Giving a quotient of 3, and a remainder of 16.

Python 3.0 compatible code

<lang python>def arithmetic(x, y):

   for op in "+ - * // %".split():
       expr = "%(x)s %(op)s %(y)s" % vars()
       print("%s\t=> %s" % (expr, eval(expr)))


arithmetic(12, 8) arithmetic(input("Number 1: "), input("Number 2: "))</lang> Output:

12 + 8  => 20
12 - 8  => 4
12 * 8  => 96
12 // 8 => 1
12 % 8  => 4
Number 1: 20
Number 2: 4
20 + 4  => 24
20 - 4  => 16
20 * 4  => 80
20 // 4 => 5
20 % 4  => 0

Raven

'  Number 1: ' print expect 0 prefer as x
'  Number 2: ' print expect 0 prefer as y

x y + "       sum: %d\n" print
x y - "difference: %d\n" print
x y * "   product: %d\n" print
x y / "  quotient: %d\n" print
x y % " remainder: %d\n" print

Ruby

<lang ruby>puts 'Enter x and y' x=gets.to_i y=gets.to_i

puts "Sum: #{x+y}",

    "Difference: #{x-y}",
    "Product: #{x*y}",
    "Quotient: #{x/y}", # truncates towards negative infinity
    "Remainder: #{x%y}" # same sign as second operand</lang>

Scheme

<lang scheme>(define (arithmetic x y)

 (for-each (lambda (op)
             (write  (list op x y))
             (display " => ")
             (write ((eval op) x y))
             (write-char #\newline))
           '(+ - * / quotient remainder modulo max min gcd lcm)))
          

(arithmetic 8 12)</lang> quotient - truncates towards 0 remainder - same sign as first operand modulo - same sign as second operand

 prints this:

(+ 8 12) => 20
(- 8 12) => -4
(* 8 12) => 96
(/ 8 12) => 2/3
(quotient 8 12) => 0
(remainder 8 12) => 8
(modulo 8 12) => 8
(max 8 12) => 12
(min 8 12) => 8
(gcd 8 12) => 4
(lcm 8 12) => 24

Smalltalk

Works with: GNU Smalltalk

<lang smalltalk>| a b | 'Input number a: ' display. a := (stdin nextLine) asInteger. 'Input number b: ' display. b := (stdin nextLine) asInteger. ('a+b=%1' % { a + b }) displayNl. ('a-b=%1' % { a - b }) displayNl. ('a*b=%1' % { a * b }) displayNl. ('a/b=%1' % { a // b }) displayNl. ('a%%b=%1' % { a \\ b }) displayNl.</lang>

Standard ML

<lang sml>val () = let

 val a = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
 val b = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))

in

 print ("a + b = "   ^ Int.toString (a + b)   ^ "\n");
 print ("a - b = "   ^ Int.toString (a - b)   ^ "\n");
 print ("a * b = "   ^ Int.toString (a * b)   ^ "\n");
 print ("a div b = " ^ Int.toString (a div b) ^ "\n");         (* truncates towards negative infinity *)
 print ("a mod b = " ^ Int.toString (a mod b) ^ "\n");         (* same sign as second operand *)
 print ("a quot b = " ^ Int.toString (Int.quot (a, b)) ^ "\n");(* truncates towards 0 *)
 print ("a rem b = " ^ Int.toString (Int.rem (a, b)) ^ "\n");  (* same sign as first operand *)
 print ("~a = "      ^ Int.toString (~a)      ^ "\n")          (* unary negation, unusual notation compared to other languages *)

end</lang>

SNUSP

As a BF derivative, SNUSP only has increment and decrement as native operations. Here are routines for other basic arithmetic upon single digit numbers and results. <lang SNUSP> $\

,
@
\=@@@-@-----#  atoi
>
,
@
\=@@@-@-----#
<
@     #        4 copies
\=!/?!/->>+>>+>>+>>+<<<<<<<<?\#
>  | #\?<<<<<<<<+>>+>>+>>+>>-/
@  |
\==/
\>>>>\
/>>>>/
@
\==!/===?\#    add
<   \>+<-/
@
\=@@@+@+++++#  itoa
.
<
@
\==!/===?\#    subtract
<   \>-<-/
@
\=@@@+@+++++#
.
!
/\
?-             multiply
\/ #/?<<+>+>-==\     /==-<+<+>>?\#    /==-<<+>>?\#
<   \->+>+<<!/?/#   #\?\!>>+<+<-/    #\?\!>>+<<-/
@         /==|=========|=====\   /-\    |
\======<?!/>@/<-?!\>>>@/<<<-?\=>!\?/>!/@/<#
<         \=======|==========/   /-\  |
@                 \done======>>>!\?/<=/
\=@@@+@+++++#
.
!
/\
?-  zero
\/
<              divmod
@    /-\
\?\<!\?/#!===+<<<\      /-\
| \<==@\>@\>>!/?!/=<?\>!\?/<<#
|      |  |  #\->->+</
|      \=!\=?!/->>+<<?\#
@            #\?<<+>>-/
\=@@@+@+++++#
.
<
@
\=@@@+@+++++#
.
#

</lang>

Tcl

<lang tcl> puts "Please enter two numbers:"

gets stdin x
gets stdin y

puts "
  $x + $y = [expr {$x + $y}]
  $x - $y = [expr {$x - $y}]
  $x * $y = [expr {$x * $y}]
  $x / $y = [expr {int($x / $y)}]
  $x mod $y = [expr {$x % $y}]
"</lang>

Since Tcl doesn't really know about the "type" of a variable, the "expr" command is used to declare whatever follows as an "expression". This means there is no such thing as "integer arithmetic" and hence the kludge int( $x / $y ).

Often, these operations would be performed in a different way from what is shown here. For example, to increase the variable "x" by the value of the variable "y", one would write

incr x $y

Also, it's important to surround the arguments to the expr in braces. Discussion is here.

Toka

[ ( a b -- )
  2dup ." a+b = " + . cr  
  2dup ." a-b = " - . cr  
  2dup ." a*b = " * . cr  
  2dup ." a/b = " / . ." remainder " mod . cr  
] is mathops

UNIX Shell

With external utilities:

Works with: Bourne shell
 #!/bin/sh
 read a; read b;
 echo "a+b     = "  `expr $a  +  $b`
 echo "a-b     = "  `expr $a  -  $b`
 echo "a*b     = "  `expr $a \*  $b`
 echo "a/b     = "  `expr $a  /  $b` # truncates towards 0
 echo "a mod b = "  `expr $a  %  $b` # same sign as first operand

(Notes: Using the ` (backtick operators, also available in most Bourne shells via the $(...) syntax) allows us to keep the results on their labels in the most efficient and portable way. The spaces around the operators in the expr command line arguments are required and the shell requires us to quote or escape the * character has shown, to prevent any possible "globbing" --- filename expansion of the * as a wildcard character.

With SUSv3 parameter expansions:

Works with: Almquist SHell
Works with: Bourne Again SHell version 3.2
Works with: Korn SHell version 5.2.14
Works with: Z SHell
 #!/bin/sh
 read a; read b;
 echo "a+b     = $(($a+$b))"
 echo "a-b     = $(($a-$b))"
 echo "a*b     = $(($a*$b))"
 echo "a/b     = $(($a/$b))" # truncates towards 0
 echo "a mod b = $(($a%$b))" # same sign as first operand

(Note: spaces inside the $((...)) are optional and not required; the $((...)) expressions can be inside the double quotes, but the `...` expressions could also have been enclosed in the double quotes in the previous example).

Vedit macro language

 #1 = Get_Num("Give number a: ")
 #2 = Get_Num("Give number b: ")
 Message("a + b = ") Num_Type(#1 + #2)
 Message("a - b = ") Num_Type(#1 - #2)
 Message("a * b = ") Num_Type(#1 * #2)
 Message("a / b = ") Num_Type(#1 / #2)
 Message("a % b = ") Num_Type(#1 % #2)

Visual Basic .NET

 Imports System.Console
 Module Module1
   Sub Main
     Dim a = CInt(ReadLine)
     Dim b = CInt(ReadLine)
     WriteLine("Sum " & a + b)
     WriteLine("Difference " & a - b)
     WriteLine("Product " & a - b)
     WriteLine("Quotient " & a / b)
     WriteLine("Integer Quotient " & a \ b)
     WriteLine("Remainder " & a Mod b)
   End Sub
 End Module

XSLT

<xsl:template name="arithmetic">
  <xsl:param name="a">5</xsl:param>
  <xsl:param name="b">2</xsl:param>
  <fo:block>a + b = <xsl:value-of select="$a + $b"/></fo:block>
  <fo:block>a - b = <xsl:value-of select="$a - $b"/></fo:block>
  <fo:block>a * b = <xsl:value-of select="$a * $b"/></fo:block>
  <fo:block>a / b = <xsl:value-of select="round($a div $b)"/></fo:block>
  <fo:block>a mod b = <xsl:value-of select="$a mod $b"/></fo:block>
</xsl:template>