I heard about this challenge online today, and thought about it for a few seconds before diving in. The object is to write a program that prints the multiplication table from 1 to 12, but that didn’t seem good enough to me. There has to be some utility to the program, not just something trivial. I wanted the user to be able to specify what size table they want.
Enter a natural number: 3 0 x 0 = 0 1 x 0 = 0 2 x 0 = 0 3 x 0 = 0 0 x 1 = 0 1 x 1 = 1 2 x 1 = 2 3 x 1 = 3 0 x 2 = 0 1 x 2 = 2 2 x 2 = 4 3 x 2 = 6 0 x 3 = 0 1 x 3 = 3 2 x 3 = 6 3 x 3 = 9
Returning 12 is certainly doable, but what about 144? While that particular input will not look very good on the command line, it still returns the result: 144 x 144 = 20736. And what about 1,000? It takes a little while, but it sure gets there. There are a couple of for loops (thus, input of 1,000 is lengthy in returning), and there’s a sanity check for negative input. Other than that, this one is very lean.
~Jonathan
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | /* * Programmer: Jonathan Landrum * Date: 10 March 2012 * * Program: times.cpp * Purpose: Returns the times table of the size the * user specifies. * * Assumptions: 1.) Input is in integer form. Real input * will cause the program to exit. */ #include <iostream> using namespace std; int main() { // Variables int input; // Introduce the program cout << "--------------------------" << endl; cout << "- Times Tables -" << endl; cout << "--------------------------" << endl; cout << endl; cout << "This program takes input" << endl; cout << "of an integer and returns" << endl; cout << "the times tables up to the" << endl; cout << "number specified." << endl; cout << endl; cout << "--------------------------" << endl; cout << endl; cout << "Enter a natural number: "; cin >> input; // Sanity check while (input < 0) { cout << endl; cout << "ERROR: Bad input" << endl; cout << "Only positive input allowed" << endl; cout << endl; cout << "Enter a natural number: "; cin >> input; } // End sanity check // Perform calculations for (int c = 0; c <= input; ++c) { for (int i = 0; i <= input; ++i) cout << i << " x " << c << " = " << i * c << "\t"; cout << endl; } // End for // Exit program cout << endl; cout << "\\\\//_ Live long and prosper." << endl; } // End main |


