Function Assignment 13 — Generate a Multiplication Table of a Given Number Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Generate a Multiplication Table of a Given Number Using a Function

📑 On this page:
  • A function that prints, not returns
  • Designing the printTable function
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to write a void function that prints rather than returns
  • How to use a loop to generate a table programmatically
  • How to format output with %2d and printf's field width
  • How to accept a "limit" parameter so the table size is configurable
  • Why printing is a side effect — and what that means for function design

A function that prints, not returns

All the functions we've written so far — add, isPrime, gcd, rectangleArea — have been "value-returning" functions. You call them, they compute something, they hand the result back. The caller decides what to do with it (print it, store it, pass it to another function). This assignment is different. printTable doesn't return a value — it prints directly to the terminal. Its output is the result, and its return type is void.

Why does this distinction matter? Because the two styles have different consequences. A value-returning function is easy to test — you compare its return value to an expected value. A printing function is harder to test, because its output goes to a stream, and you have to capture that stream to verify it. A value-returning function can be used in expressions (sum + add(a, b)), while a printing function is only useful for its side effect. These aren't just style preferences; they affect how the function can be used, and whether you can compose it with other functions.

For a multiplication table, though, printing is exactly what you want. You don't need the table as a data structure — you want it shown on screen. A void function that loops and printfs is the natural fit. This assignment is a good introduction to side-effect functions, and a reminder that not every function has to compute a value. Some just do something.

The loop inside printTable is the classic multiplication-table loop: for each i from 1 to limit, print the line n × i = n*i. The function takes two parameters — n (which number to generate the table for) and limit (how far to go). Making limit a parameter rather than a hard-coded constant gives the caller control, which is exactly what a reusable function should do.

💡 In one line: write void printTable(int n, int limit). Inside, loop i from 1 to limit and printf("%d x %2d = %3d\n", n, i, n*i). The %2d and %3d right-align the numbers so the output looks tidy.

A multiplication table for the number 7, showing rows from 7×1=7 to 7×10=70.

Designing the printTable function

Three decisions, same as always, but with one twist — the return type is void:

Part Choice Why
Function nameprintTableStarts with "print" so callers know this produces output, not a value. Alternative names: showTable, displayTable.
Parametersint n, int limitn is the number whose table we want; limit is how far to go (typically 10, but configurable).
Return typevoidThe function's job is to print, not to compute a value. void says "this is a side-effect function."

That gives us the prototype:

void printTable(int n, int limit);
                                

And the definition:

void printTable(int n, int limit) {
    for (int i = 1; i <= limit; i++) {
        printf("%d x %2d = %3d\n", n, i, n * i);
    }
}
                                

The loop is straightforward: iterate from 1 to limit, and for each i, print one line of the table. The format string "%d x %2d = %3d\n" produces output like:

7 x  1 =   7
7 x  2 =  14
7 x  3 =  21
...
7 x 10 =  70
                                

The width specifiers do the alignment: %2d right-aligns the multiplier in a field of width 2 (so "1" becomes " 1", "10" stays "10"); %3d right-aligns the product in a field of width 3. Without these, the equals signs wouldn't line up, and the output would look messy. Alignment isn't just cosmetic — it makes the table easier to scan, and makes discrepancies easier to spot.

Note that n uses plain %d, not %2d — that's deliberate, so the multiplier column is left-justified by default. If n is a single digit, the first column is narrow; if n is 100, the first column is wider, and the whole row shifts. Since all rows have the same n, they shift together, and the table still looks fine. The alignment within a row (between multiplier and product) is what matters, not the width of the first column.

🎯 Key idea: width specifiers (%2d, %3d) align the output columns. This is a small thing that makes a big difference in readability. Once you've used printf's field widths, you'll reach for them anytime you're printing columns of numbers.

Complete C Program

Program: print the multiplication table of a number

#include <stdio.h>

/* Function prototype */
void printTable(int n, int limit);

int main(void) {
    int n, limit;

    printf("Enter a number: ");
    scanf("%d", &n);

    printf("Enter the limit (how far to print): ");
    scanf("%d", &limit);

    printf("\nMultiplication table of %d up to %d:\n\n", n, limit);
    printTable(n, limit);

    return 0;
}

/* Print the table */
void printTable(int n, int limit) {
    for (int i = 1; i <= limit; i++) {
        printf("%d x %2d = %3d\n", n, i, n * i);
    }
}
                                    

And a version that prints the entire table as a grid — 10 rows by 10 columns, which is the classic school-style multiplication grid:

Variant: full 10×10 grid

#include <stdio.h>

void printGrid(int size) {
    /* Header row */
    printf("    ");
    for (int j = 1; j <= size; j++) {
        printf("%4d", j);
    }
    printf("\n    ");
    for (int j = 1; j <= size; j++) {
        printf("----");
    }
    printf("\n");

    /* Data rows */
    for (int i = 1; i <= size; i++) {
        printf("%3d |", i);
        for (int j = 1; j <= size; j++) {
            printf("%4d", i * j);
        }
        printf("\n");
    }
}

int main(void) {
    printGrid(10);
    return 0;
}
                                    

This variant does two levels of looping — one for the row number (outer), one for the column contents (inner). The header row and dashed separator line above the data make it look like a proper table. If you've seen a printed multiplication grid, this is the code to reproduce it.

And a version that returns the table as a string instead of printing it — useful if you want to log it, save it, or test it:

Variant: build the table in a buffer, then print

#include <stdio.h>

void formatTable(int n, int limit, char *buffer, int bufsize) {
    int offset = 0;
    for (int i = 1; i <= limit; i++) {
        int written = snprintf(buffer + offset, bufsize - offset,
                               "%d x %2d = %3d\n", n, i, n * i);
        if (written < 0 || written >= bufsize - offset) break;
        offset += written;
    }
}

int main(void) {
    char buffer[1024];
    formatTable(7, 10, buffer, sizeof(buffer));
    printf("%s", buffer);
    return 0;
}
                                    

This variant uses snprintf — the safe version of sprintf — to write into a character buffer. The bufsize - offset argument ensures we never overflow the buffer; if the output is larger than the buffer, the function stops early rather than risking memory corruption. For a table of 10 lines, a 1024-byte buffer is plenty. For very large tables, you'd need to allocate the buffer dynamically (with malloc) or check the return value and reallocate if needed.

Program Output

A typical run of the first program:

Enter a number: 7
Enter the limit (how far to print): 10

Multiplication table of 7 up to 10:

7 x  1 =   7
7 x  2 =  14
7 x  3 =  21
7 x  4 =  28
7 x  5 =  35
7 x  6 =  42
7 x  7 =  49
7 x  8 =  56
7 x  9 =  63
7 x 10 =  70
                                

Notice how the equals signs line up (thanks to %2d for the multiplier and %3d for the product). Without them, the output would be:

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
                                

Both are correct, but the first is much easier to read. The width specifiers cost nothing at runtime, and the visual improvement is real. That's why formatted output matters — it's not just aesthetics, it's communication.

A shorter table:

Enter a number: 3
Enter the limit (how far to print): 5

Multiplication table of 3 up to 5:

3 x  1 =   3
3 x  2 =   6
3 x  3 =   9
3 x  4 =  12
3 x  5 =  15
                                

A table with a larger multiplier:

Enter a number: 12
Enter the limit (how far to print): 5

Multiplication table of 12 up to 5:

12 x  1 =  12
12 x  2 =  24
12 x  3 =  36
12 x  4 =  48
12 x  5 =  60
                                

And the 10×10 grid variant:

       1   2   3   4   5   6   7   8   9  10
    ----------------------------------------
  1 |   1   2   3   4   5   6   7   8   9  10
  2 |   2   4   6   8  10  12  14  16  18  20
  3 |   3   6   9  12  15  18  21  24  27  30
  ...
 10 |  10  20  30  40  50  60  70  80  90 100
                                

The grid is a more comprehensive view, and it's what you'd want if you were generating a printable worksheet or checking multiplication facts across all combinations. The single-row table is what you'd want if you were drilling a specific number.

Step-by-Step Explanation

Let's walk through the first program piece by piece, and then look at some variations.

1. The prototype

void printTable(int n, int limit); — the void return type signals that this function doesn't compute a value; its purpose is its side effect (printing). Two integer parameters give it the number and the limit. This is a natural design: the caller provides the inputs, the function produces output.

2. Reading inputs

scanf("%d", &n) reads the number, and scanf("%d", &limit) reads the limit. In a real program, you'd probably combine these into one call with two format specifiers, but splitting them lets you prompt for each with a distinct message — clearer for interactive use.

3. The function call

printTable(n, limit); — call the function with the two values. Since it returns void, there's no assignment to the left. If you tried int result = printTable(n, limit);, the compiler would error: "void value not ignored as it ought to be." That's the type system protecting you — you can't accidentally try to use a nonexistent return value.

4. The loop inside the function

for (int i = 1; i <= limit; i++) — iterate from 1 to limit. This is the standard counting loop. The starting value (1) matters because multiplication tables typically start at ×1, not ×0. The ending value (limit) is the caller's choice — usually 10, but sometimes 12 or 20, depending on the convention. Making it a parameter rather than a hard-coded constant is a small but important design decision.

5. The print statement

printf("%d x %2d = %3d\n", n, i, n * i) — three format specifiers, three arguments. In order:

  • %d takes n — the base number, printed with default width.
  • %2d takes i — the multiplier, printed right-aligned in a field of width 2.
  • %3d takes n * i — the product, printed right-aligned in a field of width 3.

The x and = are literal characters — they appear between the fields, just as you'd write them on paper. The \n at the end moves to the next line.

6. Why the width specifiers matter

Without width specifiers, each line would have a different length, and the equals signs wouldn't line up. With %2d and %3d, every line has the same width, so the equals signs form a vertical column. This makes the table easy to scan, and it's the kind of detail that separates a "works" program from a "polished" one. The cost is zero — the compiler handles field widths natively.

7. The return type and its implications

Because printTable returns void, it can't be used in an expression. You can't write if (printTable(n, limit) == 0), or printf("%d", printTable(n, limit)), or sum += printTable(n, limit). The only thing you can do is call it, and let its side effect (the printing) happen. This is the tradeoff of void functions: they're simpler to write but less flexible to compose. For a print function, that's fine. For a compute function, you'd return a value.

8. What the function does at runtime

For printTable(7, 10):

  1. i = 1: prints "7 x 1 = 7"
  2. i = 2: prints "7 x 2 = 14"
  3. i = 3: prints "7 x 3 = 21"
  4. ...
  5. i = 10: prints "7 x 10 = 70"
  6. Loop ends. Function returns (implicitly — no return statement is needed).

Note that we don't need a return; at the end of a void function — reaching the closing brace is equivalent to returning. Some style guides still put an explicit return; at the end of void functions as a matter of habit, but it's optional.

9. Testing considerations

A printing function is harder to test than a value-returning one, because its "output" goes to the terminal. You can redirect the output to a file (./program > output.txt) and compare files, but that's awkward. A common pattern is to have the function take a FILE * argument — a stream to write to — which lets tests pass a memory stream. Our simplified version just uses printf, which writes to stdout. For a learning program, that's fine; for production code, you'd want the stream-agnostic version.

10. When to use void vs. return values

A general rule: use a void function when the entire purpose of the call is a side effect (printing, logging, modifying state via pointers, sending data over the network). Use a value-returning function when the caller needs the computed result for further use. For a multiplication table, the "result" is the printed output, so void is correct. For a function that computes "what would 7×5 be", returning a value is correct. The question to ask is: does the caller need the value, or just the effect? That determines the return type.

🔍 Try this: run the first program with n = 9 and limit = 15. Observe how the alignment holds — the multiplier column reaches "15", which still fits in width 2, and the product column reaches "135", which fits in width 3. Now try n = 99 and limit = 20 — the products reach "1980", which needs width 4, so the alignment shifts. Can you adjust the format specifiers to preserve alignment for larger inputs?

Frequently Asked Questions

1. Why is the return type void?

Because the function's job is to print the table, not to return a value. The result is the printed output, not a number that the caller can use. If you returned a value — say, the count of lines printed — the caller would have no use for it, since the table is already on screen. void communicates "this is a side-effect function" to the reader, and prevents accidental misuse.

2. What if the user enters a negative limit?

The loop for (i = 1; i <= limit; i++) would never execute, since 1 <= negative is false. So the function would print nothing — no error, no crash, just silence. To handle this gracefully, you'd validate the input in main and print an error message, or clamp the limit to a sensible minimum. For a learning program, silence on invalid input is acceptable; for production code, defensive validation is better.

3. What are %2d and %3d?

They're format specifiers with field widths. %2d means "print an integer in a field of at least 2 characters" — shorter numbers are right-padded with spaces, longer numbers take their natural width. %3d is the same with 3 characters. These make columns line up. If you write %d instead, the numbers appear with no padding, and columns don't align.

4. Why use the "x" character instead of "×"?

Because x is ASCII, while × (the multiplication sign, U+00D7) is Unicode. The C standard library's printf doesn't handle Unicode directly — you'd need to write raw bytes (or use a library like ICU), and the output might not display correctly in all terminals. For portability, "x" is safer. Most programmers use "x" in console output, reserving "×" for graphical interfaces where the font and rendering are under your control.

5. Can printTable return a string instead of printing?

Yes, but it's more work. You'd need to allocate a buffer (or pass one in), write into it with snprintf, and return a pointer to it. The caller would then decide what to do with the string (print it, save it to a file, send it over a network). This is the "build in a buffer, then print" pattern shown in the third variant. It's more flexible — you can reuse the table text for multiple purposes — but it introduces memory management concerns (who allocates, who frees?). For a simple print function, void is fine.

6. What if I want to print several tables side by side?

You'd need to interleave the rows. For each row i, print the i-th row of the first table, then the i-th row of the second table, then the third, etc. This requires either calling a "print one row" function for each table per iteration, or printing each table's row separately within a single row loop. The formatting gets trickier — you need to compute the width of each column so they align across tables. It's a good exercise in formatted output, but not necessary for the basic assignment.

💡 Tip: Once this works, generalize it — write a function printTables(int from_n, int to_n, int limit) that prints the tables for every number in a range. Or write printPaddedTable(int n, int limit, int colwidth) where the column widths are parameters. Each refinement teaches a bit more about how to parameterize a function so it handles more cases without needing to be rewritten. That's the essence of designing reusable APIs.

📖 Related Tutorials

  • Introduction to Functions in C
  • C For Loop
  • Basic Input/Output in C
  • Function Definition
  • Function Declaration
  • Types of Functions
  • Previous: Print All Primes Between Two Numbers Using a Function
  • All 33 Function Assignments

Previous Topic: -->> 12. Print All Prime Numbers Between Two Numbers Using a Function   ||   Next Topic: -->> 14. Check Whether a Number Is a Palindrome Using a Function


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.