What is Factorial and Binary Conversion- C Programming Training Institute In Hyderabad

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

PREV_LEC | NEXT_LEC

Factorial and Binary Conversion

Lecture 7 of our free C programming course. Write a factorial program in C, learn why data types decide how far it can go, and convert binary numbers to decimal with loops, the way embedded C programming reads register bits.

A factorial program in C is a favourite exercise because it is short, yet it teaches something that matters on every microcontroller: numbers have limits. Multiply a few small integers together and the result can silently overflow the type that holds it. In this free C tutorial lecture we write factorial loops, detect overflow before it happens, and then use the same loop thinking to convert binary numbers to decimal and to print the bits of a register value. These skills sit at the heart of embedded C programming, and they continue our free embedded C course after the digit-extraction lecture.

What You Will Learn

  • What a factorial is and how to compute it with a while loop.
  • Why factorials overflow so quickly and how to choose the right type.
  • How to detect overflow safely before multiplying.
  • How to convert binary to decimal using place values and using the shift-and-add method.
  • How to print the bits of an 8-bit register value with a mask loop.
  • Typical mistakes, best practices and interview-style questions.

Prerequisites

You need the while loop and the digit-extraction idea from the last two lectures, plus basic familiarity with integer types such as int and unsigned long long. Knowing that a byte has eight bits helps for the last section.

What Is a Factorial?

The factorial of a non-negative integer n, written n!, is the product of every whole number from 1 up to n. By convention 0! equals 1. So 5! is 5 x 4 x 3 x 2 x 1, which is 120. Factorials count the number of ways to arrange n distinct items, which is why they appear in permutation and combination problems.

How the loop builds 5 factorial

fact = 1k = 5
fact = 1 x 5 = 5k = 4
fact = 5 x 4 = 20k = 3
fact = 20 x 3 = 60k = 2
fact = 60 x 2 = 120k = 1, stop

Factorial Program in C Using a While Loop

The loop counts a helper variable down from n to 2. We skip multiplying by 1 because it changes nothing. The accumulator starts at 1, the identity for multiplication, for the same reason the digit-product program in the last lecture started at 1.

#include <stdio.h>

int main(void)
{
    int target = 5;
    unsigned long long fact = 1;
    int k = target;

    if (target < 0) {
        printf("Factorial is not defined for negative numbers\n");
        return 1;
    }
    while (k > 1) {
        fact *= k;
        k--;
    }
    printf("%d! = %llu\n", target, fact);
    return 0;
}
gcc -Wall -Wextra -std=c11 fact64.c -o fact64
./fact64
5! = 120

Two details deserve attention. First, the negative check happens before the loop, because a factorial is undefined for negative input and a loop with k > 1 would otherwise quietly return 1. Second, the copy k is used so that target survives for the final message.

Why Data Types Matter: Factorial Overflow

Factorials grow faster than almost anything you meet in everyday programming. The table shows how fast the limits of common types are exhausted.

TypeLargest valueLargest n whose n! fits
16-bit unsigned655358 (40320)
32-bit unsigned429496729512 (479001600)
64-bit unsigned1844674407370955161520

On older compilers and on many 8-bit and 16-bit microcontrollers, a plain int is only 16 bits, so even 8! overflows a signed int (its maximum is 32767). On a modern desktop int is usually 32 bits, which is why you cannot rely on the size of int in portable embedded code. Use the fixed-width types from stdint.h when the range matters.

Detecting Overflow Before It Happens

Unsigned overflow in C wraps around silently, and signed overflow is undefined behaviour. The safe habit is to test before multiplying: if fact is already larger than the maximum divided by the next factor, the product cannot fit.

#include <stdio.h>
#include <stdint.h>

int main(void)
{
    uint32_t fact = 1;
    uint32_t n = 1;

    while (n <= 15) {
        if (fact > UINT32_MAX / n) {
            printf("%u! does not fit in 32 bits, stopping\n", n);
            break;
        }
        fact *= n;
        printf("%2u! = %u\n", n, fact);
        n++;
    }
    return 0;
}
 1! = 1
 2! = 2
 3! = 6
 4! = 24
 5! = 120
 6! = 720
 7! = 5040
 8! = 40320
 9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! does not fit in 32 bits, stopping

The program stops at 13 because 13! is 6227020800, which is larger than the biggest 32-bit unsigned value. The break statement leaves the loop immediately; we cover it fully in a later lecture of this free embedded C course.

Binary to Decimal Conversion in C

A binary number is a sum of powers of two. The rightmost bit is worth 1, the next 2, then 4, 8, 16 and so on. To convert, add the weight of every bit that is 1. For 101101 the weights 32, 8, 4 and 1 are set, so the value is 45.

Place values for the binary number 101101

Bit position543210
Weight32168421
Bit101101
Contribution3208401

Method 1: Digits Written Like a Decimal Number

If the binary digits are stored in an integer that merely looks like a decimal number (the digits 1-0-1-1-0-1 stored as the number 101101), we can extract each digit with the technique from the previous lecture and multiply it by a growing place value.

#include <stdio.h>

int main(void)
{
    unsigned long long digits = 101101ULL;   /* binary digits written like a decimal number */
    unsigned long long work = digits;
    unsigned int place = 1;
    unsigned int value = 0;

    while (work > 0) {
        unsigned int bit = work % 10;
        value += bit * place;
        printf("bit=%u place=%u value=%u\n", bit, place, value);
        place *= 2;
        work /= 10;
    }
    printf("%llu in binary = %u in decimal\n", digits, value);
    return 0;
}
bit=1 place=1 value=1
bit=0 place=2 value=1
bit=1 place=4 value=5
bit=1 place=8 value=13
bit=0 place=16 value=13
bit=1 place=32 value=45
101101 in binary = 45 in decimal

This trick is good for learning but has a hard limit: the digit-style number must fit in the integer type, so a 32-bit unsigned value can hold at most ten binary digits, and even a 64-bit one only about nineteen. Real code keeps binary in text or in the number itself, not in a decimal-looking integer.

Method 2: Shift and Add on a String

A cleaner method reads the bits left to right. For each bit, double the running value and add the new bit. This is called Horner’s method, and it needs no place variable at all.

#include <stdio.h>

int main(void)
{
    const char *text = "11010";
    unsigned int value = 0;
    int i = 0;

    while (text[i] != '\0') {
        value = value * 2 + (unsigned)(text[i] - '0');
        printf("after '%c' value=%u\n", text[i], value);
        i++;
    }
    printf("\"%s\" = %u\n", text, value);
    return 0;
}
after '1' value=1
after '1' value=3
after '0' value=6
after '1' value=13
after '0' value=26
"11010" = 26

The expression text[i] - '0' converts the character ‘0’ or ‘1’ into the number 0 or 1, because the digit characters are consecutive in the character set. The loop ends at the string terminator, a zero byte, so no length variable is needed.

Printing Register Bits in Embedded C

Going the other way, from a value to its bits, is something firmware developers do constantly while debugging. A mask that starts at the top bit and moves right visits each bit in turn.

#include <stdio.h>
#include <stdint.h>

int main(void)
{
    uint8_t reg = 0x2D;
    uint8_t mask = 0x80;

    printf("0x%02X = ", reg);
    while (mask != 0) {
        putchar((reg & mask) ? '1' : '0');
        mask >>= 1;
    }
    putchar('\n');
    return 0;
}
0x2D = 00101101

The loop stops once the single set bit in mask has been shifted out and the mask becomes zero. You have just read a hardware register image bit by bit, using only a while loop and two bitwise operators.

Common Mistakes and Troubleshooting

MistakeConsequenceFix
Starting the factorial accumulator at 0Every result is 0Start at 1
Using int for large factorialsWrong numbers after overflowUse a wider unsigned type and check before multiplying
Printing a 64-bit value with %dGarbage output or compiler warningUse %llu for unsigned long long
Forgetting the negative checkFactorial of a negative number appears to be 1Reject negative input first
Typing a non-binary digit such as 2 in method 1Meaningless resultValidate every digit is 0 or 1
Overwriting the original numberOriginal lost for the final printfLoop on a copy
Warning: signed integer overflow is undefined behaviour in C. The compiler may assume it never happens and optimise your checks away. Use unsigned types for wrap-around arithmetic and test limits before the operation.

Best Practices and Performance Notes

  • Choose the type from the range you need, then document that range in a comment.
  • Prefer uint8_t, uint16_t and uint32_t in firmware so behaviour is identical across compilers.
  • For large factorials, a lookup table of precomputed values is faster and uses no loop at run time. A table of 13 entries covers every 32-bit result.
  • Use shift and add rather than repeated multiplication for powers of two; compilers do this, but writing the intent makes the code clearer.
  • Keep conversions between text and numbers inside small helper functions so they can be tested on the PC before they run on the board.

Summary and Key Takeaways

Key takeaways

  • n! is the product of 1 through n, and 0! is 1.
  • A factorial accumulator starts at 1, and the loop multiplies down to 2.
  • Factorials overflow fast: 12! is the last that fits in 32 bits, 20! the last in 64 bits.
  • Check fact > MAX / n before multiplying to detect overflow safely.
  • Binary to decimal: add the weights of the bits that are set, or use shift and add.
  • A moving mask lets you print any register as bits.

Conclusion

The factorial and binary conversion programs look small, but they teach the habits of reliable embedded C programming: pick a type with enough range, protect against overflow, work on copies, and trace loops by hand. In the final lecture of this set we meet the do-while loop, which always runs its body at least once, and finish with a quiz and interview questions covering all of the loops you have seen in this chapter of the free embedded C course.

Frequently Asked Questions

What is 0 factorial in C?

By definition 0! equals 1. A loop that multiplies from n down to 2 returns 1 for both 0 and 1, which happens to match.

Why does my factorial program print wrong values after 12?

With a 32-bit type, 13! exceeds the maximum value and wraps around. Use a 64-bit type or stop with an overflow check.

Should I use recursion or a loop for factorial in embedded systems?

A loop. Recursion consumes stack space for each call, and small microcontrollers have very little stack.

How do I convert decimal to binary in C?

Walk a mask from the highest bit to the lowest and print 1 or 0 depending on whether the bit is set, as in the register example above.

Why subtract ‘0’ from a character?

Digit characters are stored in consecutive codes, so subtracting the code of ‘0’ gives the numeric value of the digit.

Is signed overflow the same as unsigned overflow?

No. Unsigned arithmetic wraps around in a defined way. Signed overflow is undefined behaviour and should be avoided.

Finish the Loop Chapter

The last lecture covers the do-while loop, plus a quiz and interview questions for the whole set.

PREV_LEC | NEXT_LEC

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *