Pointer Assignment 29 — Factorial of a Number Using a Function and Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Factorial of a Number Using Pointers — Input by const int *, Output by unsigned long long *

📑 On this page:
  • How Pointer-Based Factorial Works
  • The Three Steps of the Factorial
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to use one pointer for input (const int *) and another for output (unsigned long long *)
  • Why factorial overflow limits the input to n ≤ 20 for 64-bit types
  • Why 0! and 1! are both 1, and how initializing the accumulator to 1 handles both
  • How to signal input errors (negative or too large) through the return value
  • How a recursive pointer-based version compares to the iterative one

How Pointer-Based Factorial Works

The factorial of a non-negative integer n, written n!, is the product of every integer from 1 to n. So 5! = 1 × 2 × 3 × 4 × 5 = 120, and by convention 0! = 1 (the empty product). Factorial grows extremely fast — 10! = 3,628,800, 13! already exceeds 32-bit signed integer range, and 21! overflows a 64-bit unsigned integer — so the result type matters as much as the loop.

This program demonstrates a pattern with two pointers on opposite sides of the function: an input pointer (const int *num) through which the function reads the number, and an output pointer (unsigned long long *out) through which it writes the result. The input pointer is const — the function promises not to modify the caller's number. The output pointer is not const — the function writes through it. This "in via one pointer, out via another" pattern is extremely common in C, because it lets a function both compute a result and signal success or failure through the return value.

The return value is used for error reporting: 0 means success, -1 means the input was negative, -2 means the input was too large to fit in unsigned long long. This is a common C idiom — the "real" output goes through pointer parameters, and the return value carries status. The caller must check the return code before trusting *out. If it doesn't check, and n was negative, *out is unchanged (or has a stale value), and the caller has a silent bug. This pattern makes error handling explicit, which is exactly what you want in numeric code.

💡 In one line: Read n through const int *, multiply an unsigned long long accumulator by 2, 3, ..., n, write the result through unsigned long long *, and return 0 (or an error code) for status.

Diagram showing a const int* input pointer feeding the factorial loop, and an unsigned long long* output pointer receiving the result, with the return value carrying a status code

The Three Steps of the Factorial

Step Pointer operation Effect
1. Validateint n = *num; then check n < 0 or n > 20Reject inputs whose factorial is undefined or would overflow
2. Multiplyunsigned long long result = 1; for (int i = 2; i <= n; i++) result *= i;Build n! by successive multiplication
3. Write and return*out = result; return 0;Deliver the result through the output pointer, signal success

The multiplier loop is the heart of the algorithm, and its bounds matter. Starting at i = 2 and going through i <= n multiplies exactly the factors 2, 3, ..., n. For n = 0 or n = 1, the loop body never runs, and result stays at its initialized value of 1 — which is correct, because 0! = 1! = 1. For n = 5, the loop runs 4 times: result = 1×2 = 2, 2×3 = 6, 6×4 = 24, 24×5 = 120. So 5! = 120. The initial value of 1 is the "empty product" — the identity element for multiplication — which is why it's the right start for the accumulator.

Overflow is the practical concern. 13! = 6,227,020,800, which exceeds INT_MAX (about 2.1 × 10⁹) on a 32-bit int — so using int for the accumulator would silently wrap, giving wrong results. unsigned long long is 64 bits on virtually every platform, and 20! = 2,432,902,008,176,640,000 fits in 64 bits (ULLONG_MAX is about 1.8 × 10¹⁹), but 21! = 51,090,942,171,709,440,000 does not. That's why the function limits input to n ≤ 20 and rejects larger inputs — a silent overflow is a far worse bug than a rejected input.

Complete C Program

Program: factorial of a number using a pointer-based function with overflow checking

#include <stdio.h>
#include <limits.h>

/* Compute n! for n = *num and write the result to *out.
   Returns 0 on success, -1 if n < 0, -2 if n > 20 (would overflow). */
int factorial(const int *num, unsigned long long *out) {
    if (num == NULL || out == NULL) {
        return -1;
    }

    int n = *num;
    if (n < 0) {
        return -1;
    }
    if (n > 20) {
        return -2;   /* 21! already overflows unsigned long long */
    }

    unsigned long long result = 1;
    for (int i = 2; i <= n; i++) {
        result *= (unsigned long long)i;
    }

    *out = result;
    return 0;
}

int main(void) {
    int values[] = {0, 1, 5, 10, 13, 20, 21, -3};
    int n = (int)(sizeof(values) / sizeof(values[0]));

    printf("Factorial results:\n");
    printf("-------------------\n");
    for (int i = 0; i < n; i++) {
        unsigned long long result = 0;
        int rc = factorial(&values[i], &result);
        if (rc == 0) {
            printf("  %2d! = %llu\n", values[i], result);
        } else if (rc == -1) {
            printf("  %2d! : undefined (negative input)\n", values[i]);
        } else if (rc == -2) {
            printf("  %2d! : too large for unsigned long long\n", values[i]);
        }
    }

    /* Interactive */
    int input;
    unsigned long long result;
    printf("\nEnter a number (0-20): ");
    if (scanf("%d", &input) == 1) {
        int rc = factorial(&input, &result);
        if (rc == 0) {
            printf("  %d! = %llu\n", input, result);
        } else {
            printf("  Cannot compute %d! (error %d)\n", input, rc);
        }
    }

    return 0;
}
                                    

Program Output

Factorial results:
-------------------
   0! = 1
   1! = 1
   5! = 120
  10! = 3628800
  13! = 6227020800
  20! = 2432902008176640000
  21! : too large for unsigned long long
  -3! : undefined (negative input)

Enter a number (0-20): 15
  15! = 1307674368000
                                

The output covers the full range of cases: the two edge cases 0! and 1! (both return 1 without entering the loop), small factorials, medium factorials (10! fits in a 32-bit unsigned int), the first factorial that requires 64 bits (13!), the largest factorial that fits in unsigned long long (20! = 2,432,902,008,176,640,000 — the exact 64-bit boundary), the first one that overflows (21!), and a negative input that's rejected. The interactive run with 15 shows a mid-range value. All the error handling is via return codes, and the caller prints an appropriate message for each case.

Step-by-Step Explanation

Let's walk through the pointer mechanics and the arithmetic.

1. The function signature

int factorial(const int *num, unsigned long long *out) has two pointer parameters plus an int return value. The input pointer const int *num is read-only: the function reads *num to get n, and never writes through this pointer. The output pointer unsigned long long *out is a place for the function to write the result. The return type int reports the status: 0 for success, -1 for a null pointer or negative input, -2 for a value too large to fit in 64 bits. This "output through pointer, status through return value" pattern is common in C because it allows both a computed value and an error code — something a single return value can't easily provide.

2. The null guards

if (num == NULL || out == NULL) return -1; catches a caller passing null pointers. Both would cause undefined behaviour if dereferenced — the input would crash on the read, and the output would crash on the write. Guarding both at the top means the rest of the function can safely dereference them. This is a "trust boundary" check: the function validates its inputs before doing anything with them, so the caller gets a clean error code instead of a segfault.

3. Reading the input

int n = *num; reads the value through the input pointer into a local int. From this point on, the function works with the local copy and doesn't touch *num again. That's fine — the input isn't modified, and the loop's variable can be a regular local. The read happens once, before validation, so all subsequent checks and computations work from the same value the caller provided.

4. Validating the range

if (n < 0) return -1; rejects negative inputs — factorial is undefined for negative integers. if (n > 20) return -2; rejects inputs whose factorial would overflow the 64-bit result type. Both checks use distinct return codes so the caller can distinguish the failure cases. If either check fails, the function returns without writing to *out, so the caller's variable is untouched — this is important: a failure shouldn't leave *out with garbage that looks like a valid result.

5. The multiplication loop

unsigned long long result = 1; initializes the accumulator to the multiplicative identity. for (int i = 2; i <= n; i++) result *= (unsigned long long)i; multiplies by each integer from 2 to n. Starting at 2 is a micro-optimization: multiplying by 1 would be a no-op, so there's no reason to iterate i = 1. The cast (unsigned long long)i ensures the multiplication is done in 64-bit arithmetic, not in int — the promotion rules would do this anyway (since result is unsigned long long), but the explicit cast makes the intent clear and avoids any subtle integer-promotion surprises.

6. Tracing 5!

n = 5, result = 1.

  • i = 2: result = 1 × 2 = 2.
  • i = 3: result = 2 × 3 = 6.
  • i = 4: result = 6 × 4 = 24.
  • i = 5: result = 24 × 5 = 120.
  • i = 6: 6 <= 5 is false, so the loop exits.

result = 120, which equals 5!. The function writes *out = 120 and returns 0 — success.

7. Tracing 0! and 1!

For n = 0, the loop condition i = 2 <= 0 is false, so the loop never runs. result stays at 1. For n = 1, the condition is 2 <= 1, also false, so again the loop doesn't run and result stays at 1. Both 0! and 1! are 1 by definition, and the loop naturally handles both without needing an explicit check. This is a nice property of starting the accumulator at 1: the empty product is 1, so zero-factor and one-factor inputs both fall out of the general logic.

8. Overflow and the "20" limit

20! = 2,432,902,008,176,640,000, which is the largest factorial that fits in an unsigned long long (which can hold up to 18,446,744,073,709,551,615 — about 1.8 × 10¹⁹ on 64-bit platforms). 21! = 51,090,942,171,709,440,000 overflows this. The check n > 20 avoids the overflow by rejecting the input before the loop runs. This is essential: if n = 21 were accepted, the loop would multiply past ULLONG_MAX, wrapping around to a small incorrect value — the caller would get a plausible-looking but completely wrong answer. Detecting the overflow up front is the only way to guarantee correct results.

9. Why the result pointer is not const

The input pointer const int *num can't be modified through — that's the contract. But the output pointer unsigned long long *out must be writeable, because the whole point of the parameter is to give the function a place to store the result. A const unsigned long long *out would be a contradiction (the function couldn't write to it). This asymmetric typing — const on the input, non-const on the output — is idiomatic in C and communicates the direction of data flow at the call site: factorial(&n, &result) clearly reads as "give the function n and a place for the result."

10. Recursive version

The factorial can also be computed recursively, and the pointer version looks like this:

unsigned long long factorial_rec(const int *num) {
    int n = *num;
    if (n <= 1) return 1;
    int n_minus_1 = n - 1;
    return (unsigned long long)n * factorial_rec(&n_minus_1);
}
                                

This version doesn't need a separate output pointer because it returns the result — the recursion handles "passing back" the intermediate values via the call stack. But it still takes const int * for the input, to satisfy the assignment's pointer requirement. The iterative version is generally preferred for factorial: it's O(1) space instead of O(n) stack space, and it's not vulnerable to stack overflow for large n (though with the n ≤ 20 limit, stack depth is at most 21, so both are fine here). The recursive version is interesting as a teaching tool because it shows how the factorial's recursive definition n! = n × (n-1)! maps directly to code.

11. Why unsigned long long and not double?

Factorials are exact integers, and double only has 53 bits of mantissa (about 15-16 decimal digits). Values like 18! = 6,402,373,705,728,000 have more significant digits than double can represent exactly — the low-order digits would be lost. Using unsigned long long keeps the exact value up to 20!, which is far more useful than a floating-point approximation. Beyond 20!, you'd need an arbitrary-precision library (like GMP) for exact results, or accept double for approximate magnitudes — both are beyond the scope of this assignment, but the point is worth knowing.

12. Complexity

Time is O(n): the loop runs n - 1 times, each iteration doing one multiplication. Space is O(1): the accumulator is one unsigned long long, and everything else is integer variables. This is optimal for computing n! iteratively — each factor must be multiplied in exactly once, and no extra storage is needed. The 64-bit accumulator makes the number of iterations bounded by 20, so in practice the function is effectively O(1), but the asymptotic O(n) is the correct way to describe it.

🎯 Remember this: Factorial of n = multiply 1 × 2 × ... × n. Use unsigned long long for the accumulator, start it at 1, reject n < 0 and n > 20 to avoid undefined and overflowed results, and pass the result back through an output pointer. Check the return code before trusting *out.

Frequently Asked Questions

1. Why does the function take both input and output pointers?

Because it has two different pieces of information to communicate: the input n needs to be passed in, and the result needs to be passed out. The input could be passed by value, but the assignment specifies a pointer-based solution, and using const int * for the input documents that the caller's n is only read. The output can't be passed by value (the function would need to return it, but then it couldn't also return an error code), so it's passed by pointer. The return value carries the status, and *out carries the result. This "in/out/status" trio is a common pattern in C APIs.

2. Why is the result type unsigned long long instead of int?

Because factorials grow very fast. 13! = 6,227,020,800 already exceeds INT_MAX (about 2.1 billion on 32-bit platforms), so using int would give wrong results at 13!. unsigned long long is 64 bits (on virtually all platforms) and can hold up to 20! exactly. That's a much better range. Even larger values (beyond 20!) would need unsigned __int128 or an arbitrary-precision library, but for this exercise, 64 bits is the right choice — it demonstrates the importance of choosing an appropriate result type.

3. Why is 0! defined as 1?

By convention, the empty product — the product of no numbers at all — is 1. This is the multiplicative identity element, just as 0 is the additive identity for sums. It's a matter of consistency: if you write n! = n × (n-1)!, then for n = 1 you get 1! = 1 × 0!, and to make this true (since 1! = 1), you need 0! = 1. The convention is universal in mathematics and computer science, and it's not just an arbitrary choice — it makes combinatorial formulas (like the binomial coefficient C(n, 0) = n!/(0!·n!) = 1) work without special cases. The program's loop initialization to 1 handles this automatically.

4. Why does the function reject n > 20?

Because 21! overflows an unsigned long long. 20! = 2,432,902,008,176,640,000, which fits in 64 bits. 21! = 51,090,942,171,709,440,000, which does not — the unsigned 64-bit max is about 1.844 × 10¹⁹. If the function didn't reject n > 20, the multiplication would silently wrap around to an incorrect (but plausible-looking) value, giving the caller wrong results without any warning. Detecting the overflow in advance — via a simple range check — is much safer than allowing silent overflow. For inputs beyond 20!, you'd need a larger type or an arbitrary-precision library.

5. Why is the input parameter const int * but the output parameter is not const?

The const on the input is a promise that the function won't modify the caller's number — it reads *num once and never writes through it. This lets the caller pass a const int (or a pointer to a variable it doesn't want changed) without warnings, and it documents the read-only intent. The output parameter can't be const, because the whole point is for the function to write the result through it. If you declared unsigned long long *const out, the const would mean the pointer itself is fixed (can't be reassigned to point elsewhere), but the function could still write through it — that's a different, subtler use of const. For a simple output parameter, plain unsigned long long * is correct.

6. What is the time and space complexity?

Time is O(n): the loop runs n - 1 times, each iteration doing one multiplication. Space is O(1): the accumulator is one unsigned long long, and everything else is integer variables. For the practical range (n ≤ 20), the function is effectively O(1) in absolute terms — the loop runs at most 19 times. But the asymptotic O(n) is the correct description for arbitrary n, and it's the right way to reason about the algorithm's scalability.

💡 Tip: Once this works, try the related problems: "n choose r" (binomial coefficient) using factorial, "permutations of n items taken r at a time" (nPr = n! / (n-r)!), and "number of trailing zeros in n!" (count factors of 5). They all build on the factorial function and use pointer-based parameter passing in the same way. The trailing-zeros problem is particularly interesting because it can be solved in O(log n) time without computing the full factorial — a good exercise in seeing past the obvious solution.

📖 Related Tutorials

  • 28. Check if a Number is Palindrome Using Pointers
  • 27. Reverse a Number Using Pointers
  • 26. Sum of Digits of a Number Using Pointers
  • 30. Swap Two Strings Using Pointers
  • Recursion in C
  • All 30 Pointer Assignments

Previous Topic: -->> 28. Check if a Number is Palindrome Using Pointers   ||   Next Topic: -->> 30. Swap Two Strings Using Pointers


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.