CSC112 Spring 2016 Examples
/* create an arbitrary multiplication table.1*/2#include <iostream>3#include <iomanip>4#include <cmath>5#include "termmanip.h"67using namespace std;89bool isPrime(int n);1011int main() {12int **table; //my table13int rows, cols; //rows and columns14int maxDigits;15int maxAnswer;1617//get the number of rows and columnns18cout << "Rows: ";19cin >> rows;20cout << "Cols: ";21cin >> cols;2223//compute the biggest24maxAnswer = rows * cols;25maxDigits = 1;26maxAnswer /= 10;27while(maxAnswer){28maxDigits++;29maxAnswer/=10;30}313233//allocate the row pointers34table = new int*[rows];3536//allocate the space for all the integers37table[0] = new int[rows * cols];3839//organize pointers so our simple fleshy brains can handle it!40for(int i=1; i<rows; i++) {41table[i] = table[i-1] + cols;42}4344//populate the table45for(int i=0; i<rows; i++) {46for(int j=0; j<cols; j++) {47table[i][j] = (i+1) * (j+1);48}49}5051//print the header52cout << reverseVideo;53cout << setw(maxDigits) << ' ';5455for(int col=1; col <= cols; col++) {56cout << setw(maxDigits+1) << col;57}58cout << ' ' << endl;59cout << normal;6061//print the rows62for(int i=0; i<rows; i++) {63cout << reverseVideo;64cout << setw(maxDigits+1) << "+" << normal;65for(int j=0; j<cols; j++) {66cout << setfill('-') << setw(maxDigits+1) << '+';67}68cout << setfill(' ') << endl;6970cout << reverseVideo;71cout << setw(maxDigits) << i+1 << "|";72cout << normal;73for(int j=0; j<cols; j++) {74if(isPrime(table[i][j])) {75cout << bold << magenta;76}77cout << setw(maxDigits) << table[i][j] << normal << "|";78}79cout << endl;80}8182cout << reverseVideo << setw(maxDigits+1) << "+" << normal;83for(int j=0; j<cols; j++) {84cout << setfill('-') << setw(maxDigits+1) << '+';85}86cout << setfill(' ') << endl;8788return 0;89}909192//check primality93bool94isPrime(int n) {95int sn;9697//handle evens98if(n%2 == 0) {99if(n == 2) {100return true;101} else {102return false;103}104}105106if(n<=1) return false;107108//check the others!109sn = (int) ceil(sqrt(n));110for(int factor=3; factor<=sn; factor+=2) {111if(n%factor == 0) return false;112}113114//if we make it here, n is prime115return true;116}117118119