Unit 1 · Lesson 318 minAcademic review pending

Arithmetic that means what you wrote

Operator precedence decides what your expression actually computes, and printf format specifiers decide whether anyone can read the result.

Choose explanation

After this lesson

You should be able to

  • Evaluate an expression using C's precedence and associativity rules.
  • Use %d, %f, %.2f, and %c correctly in printf.
  • Explain what % computes and when it is undefined.
01

Precedence is not left to right

C evaluates *, / and % before + and -. So 2 + 3 * 4 is 14, not 20. When operators have equal precedence, evaluation runs left to right: 100 / 10 / 2 is 5, because it means (100 / 10) / 2.

Parentheses override all of it, and they cost nothing. Write (a + b) / 2 even when you are sure — the next person to read your code should not have to recall a precedence table.

02

The remainder operator

% gives the remainder of integer division: 17 % 5 is 2. It works only on integers — 17.0 % 5 will not compile. It is how you test divisibility (n % 2 == 0 means even) and how you extract digits (n % 10 is the last digit).

Dividing by zero — with / or % — is undefined behaviour. The program does not reliably crash with a neat message; it may crash, may print nonsense, or may appear to work. Guard against it yourself.

/ and % working together
int seconds = 3725;
int hours   = seconds / 3600;        /* 1 */
int minutes = (seconds % 3600) / 60; /* 2 */
int rest    = seconds % 60;          /* 5 */

printf("%d h %d m %d s\n", hours, minutes, rest);
03

Format specifiers are a contract

Each % in the format string promises the type of the matching argument. %d promises an int, %f a double, %c a char. Break the promise and you get garbage, not an error — the compiler may warn, but the program will still run.

%f prints six decimals by default, which is rarely what you want. %.2f prints exactly two. %8.2f also reserves eight columns, which is how you line up a table.

Try it yourself

A shop sells an item at 249.50 rupees. Print the cost of 7 items with two decimals, and the count aligned in a 4-column field.

Need a hint?

7 is an int and 249.50 is a double. What does C do when they meet in one expression?

Check the worked solution

C promotes the int to double automatically, so count * price is real arithmetic and no cast is needed here — unlike the division case in the previous lesson, multiplication of an int by a double is already safe. %4d reserves four columns for the count and %.2f fixes the paise.

#include <stdio.h>

int main(void)
{
    int    count = 7;
    double price = 249.50;

    printf("Items: %4d\n", count);
    printf("Total: Rs. %.2f\n", count * price);

    return 0;
}

Quick check

What does printf("%d\\n", 20 - 12 / 4 * 2); print?

Select an answer to check your thinking.

Why this lesson exists

Syllabus mapping

Arithmetic Expressions · Formatting Numbers in Program Output · Executable Statements

Maps to course outcomes CO2, CO3.