Skip to content

Instantly share code, notes, and snippets.

@jwamin
Last active November 3, 2021 14:00
Show Gist options
  • Save jwamin/7befac60e5cbf21a46029ebe65e17354 to your computer and use it in GitHub Desktop.
Save jwamin/7befac60e5cbf21a46029ebe65e17354 to your computer and use it in GitHub Desktop.
Times Tables in C
#include <stdio.h>
#define LOWER 1
#define LIMIT 12
#define FORMAT "%5d"
#define MIN(a,b) (((a)<(b))?(a):(b))
void nlPrint(){
printf("\n");
}
void numberWithFormat(int number){
printf(FORMAT, number);
}
void printTTGrid(void){
int answer, i, j;
/*
0 1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
*/
//Formatting - starting x
printf("\nThe Times table grid:\n\nx - 0");
//Print first row
for (i = LOWER; i <= LIMIT; ++i) {
numberWithFormat(i);
}
nlPrint();
//O(n^2) - can we memoise this at all?
for (i = LOWER; i <= LIMIT; ++i) {
numberWithFormat(i);
for (j = LOWER; j <= LIMIT; ++j) {
answer = i * j;
numberWithFormat(answer);
}
nlPrint();
}
nlPrint();
}
void printTTFormatted(unsigned int number, unsigned int limit){
int iLimit = MIN(limit,LIMIT);
printf("The %d times table:\n\n",number);
for (int i = 1; i <= iLimit; ++i) {
printf("%d x %d = %d\n",number, i,number * i);
}
}
int main(int argc, const char** argv) {
printTTGrid();
printTTFormatted(11,60);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment