RobsonLittle 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:

1 and 6

Sum: 7
Difference: 5
Product: 6

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 arguments sent by the user when running the program.

Example usage:

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

Log

© 2004-20 robson | cc unless stated