{"id":254,"date":"2025-08-18T12:05:56","date_gmt":"2025-08-18T12:05:56","guid":{"rendered":"https:\/\/www.examtopics.biz\/blog\/?p=254"},"modified":"2026-11-04T20:16:51","modified_gmt":"2026-11-04T20:16:51","slug":"how-to-calculate-factorial-in-c-a-complete-guide","status":"publish","type":"post","link":"https:\/\/www.examtopics.biz\/blog\/how-to-calculate-factorial-in-c-a-complete-guide\/","title":{"rendered":"Factorial in C: Loop, Recursion and Overflow Checks"},"content":{"rendered":"<h2>What is a factorial in C?<\/h2>\n<p>The factorial of a nonnegative integer <code>n<\/code>, written <code>n!<\/code>, multiplies all positive integers from 1 through <code>n<\/code>. For example, <code>5! = 5 \u00d7 4 \u00d7 3 \u00d7 2 \u00d7 1 = 120<\/code>. The special cases <code>0! = 1<\/code> and <code>1! = 1<\/code> are important both mathematically and when designing a loop or recursive base case.<\/p>\n<p>In C, the arithmetic is straightforward but the data type is a major part of correctness. Standard integer types have finite ranges. A program that multiplies without checking can overflow even though every individual input looks valid. A good factorial example therefore validates the input, detects overflow <em>before<\/em> multiplication and reports a clear result.<\/p>\n<h2>A checked iterative factorial program<\/h2>\n<p>The following C11 program uses <code>unsigned long long<\/code>, checks each multiplication against <code>ULLONG_MAX<\/code>, and returns a success flag. It stores the result through an output pointer only when computation succeeds. That avoids using a numeric value such as zero to mean an error when zero is never a valid factorial result.<\/p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;limits.h&gt;\n\nint factorial_checked(int n, unsigned long long *out) {\n    if (n &lt; 0 || out == NULL)\n        return 0;\n\n    unsigned long long value = 1;\n    for (int i = 2; i &lt;= n; ++i) {\n        if (value &gt; ULLONG_MAX \/ (unsigned)i)\n            return 0;\n        value *= (unsigned)i;\n    }\n\n    *out = value;\n    return 1;\n}\n\nint main(void) {\n    int n;\n    if (scanf(\"%d\", &amp;n) != 1 || n &lt; 0) {\n        fputs(\"Enter a nonnegative integer.\\n\", stderr);\n        return 1;\n    }\n\n    unsigned long long result;\n    if (!factorial_checked(n, &amp;result)) {\n        fputs(\"Factorial exceeds the integer range.\\n\", stderr);\n        return 1;\n    }\n\n    printf(\"%d! = %llu\\n\", n, result);\n    return 0;\n}\n<\/code><\/pre>\n<p>Build this source with a C11 compiler, for example <code>cc -std=c11 -Wall -Wextra -pedantic factorial.c -o factorial<\/code>. Test zero, one and a small positive number before trying boundary values. The code&#8217;s input handling illustrates basic validation. A production command-line utility should use a carefully checked parser such as <code>strtol<\/code>, including range and trailing-character checks, for hostile or oversized numeric text.<\/p>\n<h2>How the loop works<\/h2>\n<p>The accumulator begins at 1 because 1 is the multiplicative identity. The loop runs from 2 to <code>n<\/code>, multiplying the current accumulator by each new value. For input 5, the intermediate results are 2, 6, 24 and 120. For input 0 or 1, the loop is skipped and the initialized result of 1 is returned. This design avoids special-case code in the loop itself.<\/p>\n<p>Before multiplying, the expression <code>value &gt; ULLONG_MAX \/ i<\/code> asks whether multiplying <code>value<\/code> by <code>i<\/code> would exceed the maximum value representable by <code>unsigned long long<\/code>. Checking after multiplication is too late: unsigned overflow wraps modulo its range, so the result may already have become incorrect. Signed integer overflow is even more dangerous because its behavior is undefined by C.<\/p>\n<p>The example uses an <code>int<\/code> argument to make a negative-input check easy to teach. It returns immediately on overflow, long before a loop over enormous ordinary inputs could wrap the loop counter on typical systems. For general-purpose libraries with a different argument contract, choose types and bounds according to the stated maximum input.<\/p>\n<h2>Why 20! is a useful boundary test<\/h2>\n<p>On a platform where <code>unsigned long long<\/code> is 64 bits, its maximum value is 18,446,744,073,709,551,615. In that environment, <code>20!<\/code> is 2,432,902,008,176,640,000 and fits, while <code>21!<\/code> is larger than the type&#8217;s maximum and must be rejected. C guarantees <code>unsigned long long<\/code> is at least 64 bits, but implementations can provide a wider type, so a portable program should consult <code>ULLONG_MAX<\/code> instead of assuming that 20 is the last supported input everywhere.<\/p>\n<p>The C numeric limits reference summarizes the relevant macros from <code>&lt;limits.h&gt;<\/code>. The important lesson is not to memorize a particular machine limit, but to validate against the limit of the actual type and implementation being used.<\/p>\n<h2>Recursion: the same mathematical rule with different risks<\/h2>\n<p>Factorial also follows <code>n! = n \u00d7 (n-1)!<\/code> when <code>n \u2265 2<\/code>. A simple recursive version illustrates the recurrence clearly. The following teaching function is intentionally limited to small, trusted inputs because it performs no overflow checking and each call consumes stack space.<\/p>\n<pre><code>unsigned long long factorial_small(unsigned n) {\n    if (n &lt;= 1)\n        return 1ULL;\n    return (unsigned long long)n * factorial_small(n - 1);\n}\n<\/code><\/pre>\n<p>With <code>factorial_small(5)<\/code>, the function calls itself with arguments 5, 4, 3, 2 and 1, then multiplies values while returning. The recursive form uses additional call stack for every level; C does not guarantee that a compiler will eliminate this recursion. It is not safer or necessarily faster than iteration, and passing a huge number can exhaust the stack before overflow is detected.<\/p>\n<p>For externally supplied values, the checked iterative implementation is the better starting point. A checked recursive version would need to validate the result at each multiplication and enforce a safe recursion depth, adding complexity without providing an advantage for ordinary factorial calculations.<\/p>\n<h2>Common mistakes in C factorial programs<\/h2>\n<p>Initializing the accumulator to zero causes every answer to be zero. Treating a negative number as if the loop simply ran zero times produces the false result 1. Forgetting the zero case breaks a standard factorial identity. Using <code>int<\/code> to store a large factorial causes overflow much earlier than an unsigned 64-bit result. Using a floating-point value merely to delay overflow sacrifices exact integer results.<\/p>\n<p>Another common mistake is printing a value with the wrong format specifier. For <code>unsigned long long<\/code>, the example uses <code>%llu<\/code>; using <code>%d<\/code> would not match the argument type and can produce undefined behavior. Compiler warnings help catch format mistakes, but cannot prove that arithmetic is correct for every input.<\/p>\n<p>Input parsing needs care too. <code>scanf<\/code> is convenient for a beginner, but robust software must reject malformed and out-of-range numbers explicitly. It should not accept a partially parsed prefix and silently ignore unexplained extra characters. Document whether a function accepts only decimal text, signed text or numbers from another API.<\/p>\n<h2>Test cases and expected outcomes<\/h2>\n<table>\n<thead>\n<tr>\n<th>Input<\/th>\n<th>Expected result on a 64-bit unsigned-long-long system<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>0<\/td>\n<td>1<\/td>\n<\/tr>\n<tr>\n<td>1<\/td>\n<td>1<\/td>\n<\/tr>\n<tr>\n<td>5<\/td>\n<td>120<\/td>\n<\/tr>\n<tr>\n<td>10<\/td>\n<td>3,628,800<\/td>\n<\/tr>\n<tr>\n<td>20<\/td>\n<td>2,432,902,008,176,640,000<\/td>\n<\/tr>\n<tr>\n<td>21<\/td>\n<td>Reported overflow<\/td>\n<\/tr>\n<tr>\n<td>-1<\/td>\n<td>Reported invalid input<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>These examples test normal results, the lower boundary, a high but representable value and values that must be rejected. The C program shown above was checked with a C11 compiler using these representative cases. Broader production testing should also cover text parsing, platform-specific integer widths and the calling contract of any exported function.<\/p>\n<h2>Performance and memory considerations<\/h2>\n<p>The iterative method performs a number of multiplications proportional to <code>n<\/code> until the representable limit is reached. It uses constant additional storage beyond the result and loop variables. Recursion performs similar multiplication work but uses stack frames proportional to the argument. For fixed-width integer arithmetic, checking overflow is usually more important than tuning a tiny loop.<\/p>\n<p>If an application needs larger exact factorials, choose an appropriate arbitrary-precision integer library and consider its allocation and computational cost. Do not keep widening a built-in C integer and assume it will eventually handle all inputs. Other applications need only a factorial modulo a number or a ratio of factorials; specialized algorithms can calculate those more efficiently without representing an enormous intermediate result.<\/p>\n<h2>Where factorial calculations are used<\/h2>\n<p>Factorials count arrangements of distinct objects and appear in combinations, probability distributions and series expansions. The number of permutations of <code>n<\/code> distinct objects is <code>n!<\/code>, while the number of combinations of <code>k<\/code> objects chosen from <code>n<\/code> is <code>n! \/ (k! \u00d7 (n-k)!)<\/code>. In real software, evaluate whether the final result fits the selected type before constructing multiple intermediate factorials.<\/p>\n<p>For a beginner, factorial is primarily an exercise in loops, functions, validation and algorithm termination. The reliable solution is the one that matches its declared input range and reports errors instead of producing wrapped numbers. Write the simple loop, check each multiplication, test the boundaries and only then consider alternative implementations.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What is a factorial in C? The factorial of a nonnegative integer n, written n!, multiplies all positive integers from 1 through n. For example, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[37],"tags":[],"class_list":["post-254","post","type-post","status-publish","format-standard","hentry","category-programming-development"],"_links":{"self":[{"href":"https:\/\/www.examtopics.biz\/blog\/wp-json\/wp\/v2\/posts\/254","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.examtopics.biz\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.examtopics.biz\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.examtopics.biz\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.examtopics.biz\/blog\/wp-json\/wp\/v2\/comments?post=254"}],"version-history":[{"count":5,"href":"https:\/\/www.examtopics.biz\/blog\/wp-json\/wp\/v2\/posts\/254\/revisions"}],"predecessor-version":[{"id":6749,"href":"https:\/\/www.examtopics.biz\/blog\/wp-json\/wp\/v2\/posts\/254\/revisions\/6749"}],"wp:attachment":[{"href":"https:\/\/www.examtopics.biz\/blog\/wp-json\/wp\/v2\/media?parent=254"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.examtopics.biz\/blog\/wp-json\/wp\/v2\/categories?post=254"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.examtopics.biz\/blog\/wp-json\/wp\/v2\/tags?post=254"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}