- The five arithmetic operators:
+,โ,*,/,% - How integer division (
5 / 2 = 2) differs from floating-point division (5.0 / 2.0 = 2.5) - Why
%only works on integers, not ondouble - How to format each operation's output for clarity
- How to check for division by zero before dividing
- How implicit and explicit type conversions change the results
The five basic arithmetic operators
C has five arithmetic operators, and they behave differently depending on the types of their operands:
| Operator | Name | Example (int) | Example (double) |
|---|---|---|---|
+ | Addition | 5 + 2 = 7 | 5.5 + 2.0 = 7.5 |
โ | Subtraction | 5 โ 2 = 3 | 5.5 โ 2.0 = 3.5 |
* | Multiplication | 5 * 2 = 10 | 5.5 * 2.0 = 11.0 |
/ | Division | 5 / 2 = 2 (truncated) | 5.5 / 2.0 = 2.75 |
% | Modulus (remainder) | 5 % 2 = 1 | Not valid |
The crucial distinction is between integer and floating-point arithmetic. With two integer operands, + โ * / % all produce integer results โ including division, which truncates the fractional part. 5 / 2 = 2, not 2.5. This is often surprising to beginners, and it's the single most common source of subtle arithmetic bugs in C.
With at least one floating-point operand, the integer is promoted to floating-point and the operation proceeds in floating-point. So 5 / 2.0 = 2.5. That's because the 5 is converted to 5.0 first (a rule called "usual arithmetic conversions"), and then 5.0 / 2.0 gives 2.5.
The % modulus operator gives the remainder of integer division: 5 % 2 = 1 because 5 divided by 2 is 2 remainder 1. It only works on integers โ applying % to a double is a compile error. For floating-point remainder, you'd use fmod from <math.h>.
๐ก In one line: + โ * / work on both integers and doubles, but the result type depends on the operands. % only works on integers. Division with two integers truncates โ use a double to get a fractional result.
How types affect the result
The type of the result of a op b follows the "usual arithmetic conversions": if either operand is double, the other is promoted to double and the result is double. If either is float, the result is float. Otherwise, both operands are integers, and they're promoted to a common integer type (usually int), and the result is an integer.
In practice, for two int operands, a op b gives an int. For two double operands, it gives a double. For mixed operands (one int, one double), it gives a double. The last case is the source of most "surprises" โ mixing types is fine, but the result is always the "wider" of the two types.
What about overflow? int has a range of about ยฑ2.1 billion (on 32-bit systems). 2,000,000,000 + 2,000,000,000 overflows to โ294,967,296 โ undefined behavior in the standard, wraparound in practice. double has a much wider range (ยฑ10308), so overflow is almost never a concern for realistic inputs. But double loses precision for very large values โ up to about 15 significant decimal digits.
The lesson: choose types based on the range and precision you need. For simple arithmetic on small numbers, int is fine. For anything involving division or fractional values, double is safer. Mixing types is legal, but be aware of what the result type will be.
๐ฏ Key idea: the result type of a op b is the "wider" of the two operand types. int op int = int, double op double = double, int op double = double. This matters most for division: int / int truncates; double / int doesn't.
Complete C Programs
Here is the complete program, performing all four operations on two double inputs:
Program: all four operations on two doubles
#include <stdio.h>
int main(void) {
double a, b;
printf("Enter two numbers: ");
if (scanf("%lf %lf", &a, &b) != 2) {
printf("Error: invalid input.\n");
return 1;
}
printf("\n--- Results ---\n");
printf("a + b = %.2lf\n", a + b);
printf("a - b = %.2lf\n", a - b);
printf("a * b = %.2lf\n", a * b);
/* Division: check for zero before dividing */
if (b != 0.0) {
printf("a / b = %.2lf\n", a / b);
} else {
printf("a / b = undefined (division by zero)\n");
}
return 0;
}
This version reads two double values, computes the four basic operations, and prints each with two decimal places. The division check prevents division by zero โ a common source of program crashes (technically, division by zero is undefined behavior in C, and on most systems it causes a crash or a SIGFPE signal).
And here's a side-by-side comparison that runs the same operations on int and double inputs, highlighting the difference in division and showing the modulus operator:
Variant: side-by-side int vs. double
#include <stdio.h>
int main(void) {
int ia, ib;
double da, db;
printf("Enter two integers: ");
scanf("%d %d", &ia, &ib);
printf("Enter two doubles: ");
scanf("%lf %lf", &da, &db);
printf("\n--- Integer arithmetic ---\n");
printf("%d + %d = %d\n", ia, ib, ia + ib);
printf("%d - %d = %d\n", ia, ib, ia - ib);
printf("%d * %d = %d\n", ia, ib, ia * ib);
if (ib != 0) {
printf("%d / %d = %d (integer division, truncated)\n", ia, ib, ia / ib);
printf("%d %% %d = %d (remainder)\n", ia, ib, ia % ib);
} else {
printf("Division by zero โ skipping / and %%\n");
}
printf("\n--- Double arithmetic ---\n");
printf("%.2lf + %.2lf = %.2lf\n", da, db, da + db);
printf("%.2lf - %.2lf = %.2lf\n", da, db, da - db);
printf("%.2lf * %.2lf = %.2lf\n", da, db, da * db);
if (db != 0.0) {
printf("%.2lf / %.2lf = %.4lf (floating-point division)\n", da, db, da / db);
} else {
printf("Division by zero โ skipping /\n");
}
return 0;
}
The comparison is instructive. With integers 5 and 2, the division gives 2 (not 2.5), and the modulus gives 1. With doubles 5.0 and 2.0, the division gives 2.5000, and there's no modulus (you'd use fmod from <math.h> for that). Both programs do the same "operations" โ but the results are very different because of the types.
Note the format string in the modulus line: "%d %% %d = %d\n". The %% is an escaped percent sign, printed as a literal %. Without the double-percent, printf would try to interpret % as the start of a format specifier โ undefined behavior.
Program Output
Here is typical output from the first program:
Enter two numbers: 7.5 2.0
--- Results ---
a + b = 9.50
a - b = 5.50
a * b = 15.00
a / b = 3.75
Check: 7.5 + 2.0 = 9.50, 7.5 โ 2.0 = 5.50, 7.5 ร 2.0 = 15.00, 7.5 / 2.0 = 3.75. All correct.
And the side-by-side output:
Enter two integers: 7 2
Enter two doubles: 7.5 2.0
--- Integer arithmetic ---
7 + 2 = 9
7 - 2 = 5
7 * 2 = 14
7 / 2 = 3 (integer division, truncated)
7 % 2 = 1 (remainder)
--- Double arithmetic ---
7.50 + 2.00 = 9.50
7.50 - 2.00 = 5.50
7.50 * 2.00 = 15.00
7.50 / 2.00 = 3.7500 (floating-point division)
Compare the two divisions: 7 / 2 = 3 (truncated from 3.5), and 7.5 / 2.0 = 3.75 (exact). The types matter. For int, the remainder is 1 (7 % 2). For double, there's no modulus โ you'd use fmod(7.5, 2.0) = 1.5 if you wanted the floating-point remainder.
With division by zero:
Enter two numbers: 5.0 0
--- Results ---
a + b = 5.00
a - b = 5.00
a * b = 0.00
a / b = undefined (division by zero)
The check if (b != 0.0) prevents the division by zero, printing "undefined" instead of crashing. Without the check, the program would crash with SIGFPE (a floating-point exception signal) on most Unix systems, or would print "inf" (infinity) on systems that support IEEE 754 infinity.
And with negative numbers:
Enter two numbers: -10.5 4.0
--- Results ---
a + b = -6.50
a - b = -14.50
a * b = -42.00
a / b = -2.63
All operations handle negatives naturally. Check: -10.5 + 4 = -6.5, -10.5 โ 4 = -14.5, -10.5 ร 4 = -42.0, -10.5 / 4 = -2.625 (rounded to -2.63 with %.2lf). Correct.
๐ Try this: run the side-by-side version with 7 and 2 for integers, and 7.0 and 2.0 for doubles. Note the integer division (3) vs. the floating division (3.5000). Then try 5 and 2 โ the integer gives 2, while the float gives 2.5000. The fractional part is discarded in the integer case. That's the "integer division" gotcha every C beginner must internalize.
Step-by-Step Explanation
Let's walk through the side-by-side program, since it demonstrates both cases.
1. The declarations
int ia, ib; โ two integer variables for the int arithmetic. double da, db; โ two double variables for the double arithmetic. The names use i and d prefixes to distinguish the int and double variants, a common naming convention in tests and comparisons.
2. Reading the inputs
Two separate prompts and reads โ one for integers, one for doubles. The format specifiers match the types: %d for int, %lf for double. The & passes addresses so scanf can write to the variables.
3. The integer operations
For ia = 7, ib = 2:
ia + ib = 9โ 7 + 2 = 9.ia - ib = 5โ 7 โ 2 = 5.ia * ib = 14โ 7 ร 2 = 14.ia / ib = 3โ 7 รท 2 = 3.5, truncated to 3. Not 4 (no rounding โ truncation toward zero).ia % ib = 1โ 7 รท 2 = 3 remainder 1.
The truncation in division is the key point. 7 / 2 gives 3, not 3.5. In other words, int division rounds toward zero, discarding the fractional part. This is not the same as "rounding down" for negative numbers โ for โ7 / 2, the result is โ3, not โ4 (rounding toward zero, not down). This is a subtle but important detail.
4. The double operations
For da = 7.5, db = 2.0:
da + db = 9.5โ 7.5 + 2.0 = 9.5.da - db = 5.5โ 7.5 โ 2.0 = 5.5.da * db = 15.0โ 7.5 ร 2.0 = 15.0.da / db = 3.75โ 7.5 รท 2.0 = 3.75. Exact, no truncation.
There's no % for doubles. If you wanted a floating-point remainder, use fmod(da, db) from <math.h>. For 7.5 and 2.0, fmod(7.5, 2.0) = 1.5 (since 7.5 โ 3 ร 2.0 = 1.5).
5. The output format specifiers
Each line uses a different format specifier:
%dforintโ prints a signed decimal integer.%lffordoubleโ prints a double in fixed-point notation (six decimal places by default).%.2lfโ two decimal places.%.4lfโ four decimal places, for the quotient to show its precision.%%โ an escaped percent sign, for the modulus line.
Using the wrong specifier is undefined behavior. printf("%d", da) where da is a double would reinterpret the 8 bytes of the double as a 4-byte int, producing garbage. Similarly, printf("%f", ia) would interpret the 4 bytes of the int as a double โ reading 8 bytes when only 4 are valid, giving gibberish. Always match specifier to type.
6. Division by zero
The check if (ib != 0) (or if (db != 0.0)) prevents division by zero. In C, integer division by zero is undefined behavior โ on most systems, it triggers a SIGFPE signal (even though it's not really a "floating point" error; the signal name is historical). Floating-point division by zero is also undefined behavior in the standard, but on systems with IEEE 754 (which most are), it returns infinity or NaN, and doesn't crash.
Both cases are problems. The first can crash your program; the second can produce misleading output (inf or NaN). Checking for zero before dividing avoids both.
7. Type promotion in mixed expressions
What if you write ia / ib but declare ib as double? Then the int ia is promoted to double, and the division is floating-point. So int / double = double. This is called "usual arithmetic conversions" โ the integer operand is widened to match the floating-point one.
The conversions apply left-to-right through the expression. In ia / ib + ic, if ia is int and ib is double, then ia / ib is double, and adding ic (int) gives double (int promoted). If all three are int, everything is int. Understanding these promotions is key to reasoning about mixed-type expressions.
8. Overflow and precision
For integer arithmetic, overflow is undefined behavior. 2,000,000,000 + 2,000,000,000 = 4,000,000,000 exceeds INT_MAX (2,147,483,647), and on most two's-complement systems wraps around to a negative number. On some systems or with aggressive optimization, the compiler may produce completely wrong code. The fix is to use a wider type (long long) or check for overflow explicitly.
For floating-point arithmetic, overflow is also undefined behavior, but the range is much wider (ยฑ10308), so it rarely matters in practice. Precision, however, is a subtler issue: double holds about 15 significant decimal digits. Operations like 0.1 + 0.2 don't give exactly 0.3 (they give 0.30000000000000004). For most applications, this is fine, but for financial or scientific computing, you might need to be careful.
9. The modulus operator
% gives the remainder of integer division: 7 % 2 = 1, 7 % 3 = 1, 7 % 7 = 0. For negative operands, the result is implementation-defined until C99, which mandates truncation toward zero: โ7 % 2 = โ1 (since โ7 = โ3 ร 2 + (โ1)). This is a subtlety worth knowing if you'll ever use % with negatives.
% is used for many things: checking if a number is even (n % 2 == 0), extracting digits (n % 10 gives the last digit), cyclic behaviors (clock arithmetic). It's one of C's most versatile operators, but only for integers. For floating-point remainder, use fmod.
10. Extending the program
The natural extension is to add more operations: exponentiation (using pow from <math.h>), square root (sqrt), or bitwise operations (&, |, ^, <<, >>) for integers. A calculator program is a classic exercise that combines arithmetic, input handling, and (eventually) loops and conditionals โ a good next step after this one.
๐ฏ Key idea: the same operator can produce different results depending on the operand types. 7 / 2 with two integers gives 3; 7.0 / 2.0 with two doubles gives 3.5. This is not a bug โ it's how C works. Understanding type-based behavior is the difference between writing code that works and code that "mostly works."
Frequently Asked Questions
1. Why does 7 / 2 give 3 and not 3.5?
Because 7 and 2 are both int, so the division is integer division โ the result is an int, and the fractional part is truncated. For a floating-point result, use at least one double operand: 7.0 / 2.0, 7 / 2.0, or (double)7 / 2. All give 3.5. The integer-division behavior is by design โ it's how C's arithmetic works.
2. What does % do, and why can't I use it with doubles?
% gives the remainder of integer division: 7 % 2 = 1, 10 % 3 = 1, 15 % 5 = 0. It only works on integers because floating-point division doesn't have a "remainder" in the same sense. For floating-point remainder, use fmod(x, y) from <math.h>, which returns the remainder of x / y as a double. For example, fmod(7.5, 2.0) = 1.5.
3. What happens if I divide by zero?
Integer division by zero is undefined behavior โ on most systems, it triggers a SIGFPE signal (a crash), even though the signal name suggests floating-point. Floating-point division by zero is also undefined behavior, but on IEEE 754 systems (which most are), it returns infinity or NaN, no crash. Both cases are problems. Always check for zero before dividing: if (b != 0) quotient = a / b;
4. Why are the results of int and double different for the same operation?
Because C arithmetic follows the operand types. When both operands are int, the operation is integer arithmetic โ no fractional parts, potential overflow, truncation in division. When at least one operand is double, the other is promoted to double, and the operation is floating-point โ fractional parts preserved, wider range, potential rounding errors. This type-driven behavior is central to C โ it's not a bug, it's how the language works.
5. What happens if the input is very large?
For int, values beyond ยฑ2.1 billion (on 32-bit systems) overflow โ undefined behavior, wraparound in practice. For double, values beyond about 10308 overflow to infinity (or undefined behavior). To handle larger values, use long long for integers (up to about 9.2 quintillion) or long double for higher-precision floating-point. For truly arbitrary precision, you'd need a bignum library like GMP. For the small numbers in typical exercises, neither int nor double overflows.
6. Why does printf need a different format specifier for each type?
Because the binary representation of an int and a double are completely different โ an int is a two's-complement bit pattern, a double is an IEEE 754 floating-point pattern. printf uses the format specifier to know how to interpret the bytes. Passing the wrong type to printf is undefined behavior โ the function reads the wrong number of bytes and interprets them wrong, producing garbage. Always match the specifier to the type: %d for int, %f or %lf for double, %s for string, etc.
๐ก Tip: once this works, extend it to a mini calculator that asks the user which operation to perform (+, -, *, /, %), then reads two numbers and prints the result. You'll need a switch statement or an if/else chain, and you'll need to handle operator-specific constraints (like % only for integers). That's the natural next exercise โ a real calculator, not just a set of side-by-side demos.