Friday 10 February 2017

Display Multiplication Table Of a Given Number in C


Multiplication Tables for a number in mathematics is multiplication with 1 to 10 to that number


/* for multiplication table of a given number */
/*
 * num    : provided number
 * table  : result multiplication table
 * size   : size of provided table to avoid out of bound for array
*/
int multiplication_table(unsigned int num, unsigned int table[] , size_t size){
        int i=0;
        for( i=0; i < 10; i++){
                table[i] = num* (i+1);
        }
        return i;
}

Complete Code


#include <stdio.h>
#include <stdlib.h>

int multiplication_table(unsigned int num, unsigned int table[] , size_t size){
        int i=0;
        for( i=0; i < 10; i++){
                table[i] = num* (i+1);
        }
        return i;
}

int print_multiplication_table(unsigned int num, unsigned int table[], size_t size){
        int i=0;
        for( i=0; i < size; i++){
                printf("%d\tX\t%d\t=\t%d\n", num, i+1, table[i]);
        }
        return i;
}

int main(int argc, char *argv[]){
        if(argc != 2){
                fprintf(stderr, "USAGE: %s \n", argv[0]);
                return -1;
        }
        int number=0;
        number = atoi(argv[1]);
        if(number < 1){
                fprintf(stderr, "Please Enter a Positive Number\n");
                return -1;
        }
        unsigned int table[10]={0x00};
        multiplication_table(number, table, 10);
        print_multiplication_table(number, table, 10);
        return 0;
}

Compile and Output


rajesh@ideapad:~/Rajesh/Blog/math$ gcc multiplication_table.c
rajesh@ideapad:~/Rajesh/Blog/math$ ./a.out 
USAGE: ./a.out 
rajesh@ideapad:~/Rajesh/Blog/math$ ./a.out 0
Please Enter a Positive Number
rajesh@ideapad:~/Rajesh/Blog/math$ ./a.out -12
Please Enter a Positive Number
rajesh@ideapad:~/Rajesh/Blog/math$ ./a.out 12
12 X 1 = 12
12 X 2 = 24
12 X 3 = 36
12 X 4 = 48
12 X 5 = 60
12 X 6 = 72
12 X 7 = 84
12 X 8 = 96
12 X 9 = 108
12 X 10 = 120

No comments:

Post a Comment