What is C Integer Arithmetic Basics-Free Online C Programming Course

Need Help or More Information?

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

Free C Programming Course • Chapter 4 • Lecture 2

C Integer Arithmetic Basics

Why 23 / 5 is 4, what 23 % 5 really gives, and how embedded programmers use both. A hands-on lecture from our free C tutorial series.

int
In, int out: always
4
Working examples
0
Allowed divisors: never zero

In this lecture of our free C programming course we focus on integer arithmetic, the most common kind of math in firmware, drivers and system code. Most beginners trip over integer division in their first week. This free C tutorial shows exactly what the compiler does, with programs you can run and verify yourself.

What You Will Learn in This Free C Course

  • What integer arithmetic is and why the result is always an integer
  • How integer division truncates the fractional part
  • What the modulus operator returns, including for negative numbers
  • The identity that ties division and modulus together
  • Practical patterns: time conversion, digit extraction, wrap-around indexes
  • Dangers: division by zero and signed overflow

Prerequisites

Lecture 1 of this chapter (operators and arithmetic operators) and basic knowledge of int, printf and loops.

What Is Integer Arithmetic in C?

When both operands are integers, the operation is called integer arithmetic and the result is always an integer. C never quietly promotes the answer to a decimal just because the real-world answer has one. If you ask for 23 / 5, you get the whole-number quotient 4. The 0.6 is simply thrown away.

Take a = 23 and b = 5:

ExpressionResultExplanation
a + b28Plain addition
a – b18Plain subtraction
a * b115Plain multiplication
a / b4Fraction truncated (4.6 becomes 4)
a % b3Remainder: 23 – 4 × 5
How 23 / 5 and 23 % 5 split the same division
Dividend: 23 Divisor: 5
23 / 5 gives Quotient: 4 23 % 5 gives Remainder: 3
Check: 4 * 5 + 3 = 23

Integer Division Truncation Explained

Integer division discards the decimal part; it does not round. So 9 / 10 is 0, 19 / 10 is 1, and 99 / 10 is 9. Truncation is not a bug. It is exactly what you want when counting whole things: how many full hours in 7384 seconds, how many complete 512-byte sectors in a buffer.

Negative Operands

Since C99 (and in every modern compiler) division truncates toward zero, and the sign of the remainder follows the dividend. So -7 / 2 is -3 and -7 % 2 is -1. Older C89 compilers were allowed to choose differently, so portable old code sometimes avoids negative division. The identity (a / b) * b + a % b == a always holds.

The Modulus Operator Deep Dive

The modulus operator % gives the remainder after integer division. It needs integer operands on both sides. Its classic jobs are listed below.

TaskExpressionIdea
Is n even?n % 2 == 0Even numbers leave remainder 0
Last digitn % 10Remainder after removing tens
Drop last digitn / 10Truncating division
Wrap an index(i + 1) % NCircular buffers, round-robin
Clock wrapminutes % 60Leftover minutes
Both division and modulus need a non-zero second operand. Dividing an integer by zero is undefined behaviour in C. On many CPUs it raises a hardware fault; on a microcontroller without a trap handler it can hang the firmware.

Hands-On Integer Arithmetic Examples

Compile every program with gcc -Wall -Wextra -std=c11 file.c -o out.

Example 1: Seconds to Hours, Minutes, Seconds

/* cp4_2_ex1.c */
#include <stdio.h>

int main(void)
{
    int total = 7384;
    int hours = total / 3600;
    int rest  = total % 3600;
    int mins  = rest / 60;
    int secs  = rest % 60;

    printf("%d seconds = %dh %dm %ds\n", total, hours, mins, secs);
    return 0;
}
7384 seconds = 2h 3m 4s

Division gives the whole hours, modulus gives what is left over. Repeat the same trick for minutes. This is exactly how a firmware uptime counter is formatted.

Example 2: Digit Sum and Reverse of a Number

/* cp4_2_ex2.c */
#include <stdio.h>

int main(void)
{
    int n = 4521;
    int sum = 0, rev = 0;

    while (n > 0) {
        int d = n % 10;
        sum = sum + d;
        rev = rev * 10 + d;
        n = n / 10;
    }
    printf("Digit sum = %d\n", sum);
    printf("Reversed  = %d\n", rev);
    return 0;
}
Digit sum = 12
Reversed  = 1254

Example 3: Circular Index Wrap-Around

/* cp4_2_ex3.c */
#include <stdio.h>

#define SLOTS 4

int main(void)
{
    for (int i = 0; i < 10; i = i + 1) {
        printf("%d ", i % SLOTS);
    }
    printf("\n");
    return 0;
}
0 1 2 3 0 1 2 3 0 1

The same expression keeps a ring buffer head within its array, which you will see in UART drivers and logging code.

Example 4: Negative Numbers and the Identity

/* cp4_2_ex4.c */
#include <stdio.h>

int main(void)
{
    int a = -7, b = 2;

    printf("%d / %d = %d\n", a, b, a / b);
    printf("%d %% %d = %d\n", a, b, a % b);
    printf("check: %d\n", (a / b) * b + a % b);
    return 0;
}
-7 / 2 = -3
-7 % 2 = -1
check: -7

Real-World Uses You Will Meet After This Free C Programming Course

  • Embedded systems: baud-rate divisors, timer prescaler math, round-robin task slots, converting tick counts to milliseconds.
  • Linux programs: turning byte counts into page counts, splitting file offsets into block number and in-block offset.
  • General software: pagination, checksums, hash-table bucket selection.

Common Mistakes and Troubleshooting

MistakeSymptomFix
Expecting 7 / 2 to be 3.5Prints 3Make one operand floating point (next lecture)
Division by zeroCrash or “Floating point exception”Test the divisor before use
Averaging with intsAverage is too lowCast before dividing
Signed overflowUndefined behaviourUse a wider type or range-check first
Assuming % is always positiveNegative remainderAdd the divisor if you need a non-negative result

Best Practices and Safety Considerations

  • Guard every division: if (b != 0) { ... }.
  • Use unsigned types for values that can never be negative, such as counters and indexes.
  • Remember that INT_MAX + 1 on a signed int is undefined behaviour; check ranges when handling external input, as attackers abuse overflow.
  • Performance: division and modulus are the slowest integer operations. When the divisor is a power of two, compilers turn them into cheaper shifts and masks for unsigned values.

Key Takeaways

  • int op int always gives an int.
  • Division truncates toward zero; modulus returns the remainder.
  • (a / b) * b + a % b == a always holds.
  • The divisor of / and % must never be zero.

Conclusion: Keep Going in the Free C Programming Course

Integer arithmetic looks simple, yet it hides the first real trap in C: silent truncation. Once you understand quotient and remainder as a pair, a huge range of embedded and system problems become short loops. Next in the free C programming course we move to floating-point and mixed-mode arithmetic.

Quick Quiz

  1. What is 47 / 10 in C?
    Show answer4.
  2. What is 47 % 10?
    Show answer7.
  3. What does -9 / 4 give in modern C?
    Show answer-2 (truncation toward zero).
  4. Can the second operand of % be zero?
    Show answerNo. It is undefined behaviour.
  5. Which expression tests whether n is odd?
    Show answern % 2 != 0.

Interview Questions

  1. What does integer division return in C, and how is it different from rounding?
  2. How do you reverse the digits of a number without converting it to a string?
  3. What is the sign of -7 % 3 in C99, and why?
  4. How would you wrap an index in a circular buffer?
  5. Why is signed integer overflow dangerous?

Frequently Asked Questions

Does this free C programming course cover embedded use cases?

Yes. Examples such as ring buffers, time conversion and counters come straight from embedded and Linux work.

Why does 5 / 2 give 2 in C?

Both operands are integers, so C performs integer division and discards the fraction.

How do I get 2.5 from 5 / 2?

Make at least one operand floating point, for example 5.0 / 2. This is covered in the next lecture.

What does the % operator do?

It returns the remainder of integer division, such as 17 % 5 equals 2.

What happens when I divide by zero?

Integer division by zero is undefined behaviour. Programs typically crash, so always validate the divisor.

Is this free C tutorial enough to start embedded programming?

It is a solid foundation. Continue through the later chapters on pointers, bitwise operators and memory for firmware work.

Continue the Free C Programming Course

Next: floating-point arithmetic and mixed-mode expressions, and how to finally get 2.5 out of 5 / 2.

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 *