# Robson » Little Red Book » Arithmetic

## Chapter 1 - Question 1

Given two integers, output their sum, difference and product.

### Solution 1

PHP:

`<?`
`    // two integers, these can be any numbers`
`    // the numbers are randomly generated to add some variety`
`    // mt_rand() is a faster version of rand()`
`    \$a = mt_rand(1, 10);`
`    \$b = mt_rand(1, 10);`
` `
`    // show what the numbers are`
`    echo \$a . ' and ' . \$b . '<br /> <br />';`
`    // first, output their sum`
`    echo 'Sum: ' . (\$a + \$b) . '<br />';`
`    // second, output the difference`
`    // abs() is used in case the second number is greater than the first`
`    echo 'Difference: ' . abs(\$a - \$b) . '<br />';`
`    // finally, output the product`
`    echo 'Product: ' . (\$a * \$b);`
`?>    `

Which produces:

3 and 5

Sum: 8
Difference: 2
Product: 15

### Solution 2

C++:

`#include <stdio.h>`
`#include <stdlib.h>`
` `
`int main ()`
`{`
`    int num1, num2;`
`    `
`    printf("Enter a number\n>");`
`    scanf("%d", &num1);`
`    printf("Enter another number\n>");`
`    scanf("%d", &num2);`
`    `
`    printf("Sum: %d", num1 + num2);`
`    printf("\nDifference: %d", abs(num1 - num2));`
`    printf("\nProduct: %d", num1 * num2);`
` `
`    return 0;`
`}`

### Solution 3

I've written another C++ solution now that I know a little bit more about the language. This uses more compact code and arguements sent by the user when running the program.

Example usage:

`C:\code>arithmetic 9 2Sum: 11Difference: 7Product: 18C:\code>`
`#include <stdio.h>`
`#include <stdlib.h>`
` `
`using namespace std;`
` `
`int main(int argc, char *argv[])`
`{`
`    int n1 = atoi(argv), n2 = atoi(argv);`
`    printf("Sum: %d\nDifference: %d\nProduct: %d", n1 + n2, abs(n1 - n2), n1 * n2);`
`}`

## Log

• May 9, 2005 - Added solution 3.
• Apr 21, 2005 - Added solution 2.
• Jan 30, 2005 - Added solution 1.
© 2004-19 robson | cc unless stated