Computing with Operators: Precedence and Associativity

UPI Study › Courses › Programming in C › Free lessons › Lesson 2.5 Free with a free account

Computing with Operators: Precedence and Associativity

Programming in C · Chapter 2: C Language Setup, Data Types, Variables, and Console I/OSection 2.5 · lesson 12 of 787 min · free with a free account

← Numeric Data Representation in CNext lesson: Complete Data Type Reference in C →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

In this lesson

Use C's arithmetic operators and predict the order they run in.

  • Use C's five arithmetic operators, including integer division and remainder
  • Predict division and remainder results with negative operands
  • Apply precedence and associativity to evaluate expressions
  • Use parentheses and decimal constants to get the intended result

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (909 words). Read along, or search it.

Opening Problem

Sharing Seventeen Tokens Fairly

Seventeen tokens, five players, and nobody may break a token in half. How many does each player get, and how many are left over? You solved this years ago, with the words goes into and remainder. C has an operator for each of those ideas. Plus one important rule: when a line holds several operations, C does not simply go from left to right.

Arithmetic Operators

Five Operators and Their Operands

An operator is a symbol that does something to values. The values it works on are its operands. And the whole piece, such as tokens plus players, is an expression: something C works out to one value. C has five arithmetic operators: add, subtract, multiply, divide, and remainder. Multiply is a star, because the letter x could be a variable's name. Run it. Seventeen plus five is 22, minus five is 12, times five is 85. But seventeen divided by five gives 3, not 3.4. And the remainder is 2. Only the last line, with a decimal point in 17.0, gives 3.40.

Integer Division

Whole Groups and the Remainder

Here's the rule. When both numbers are whole numbers, ints, the slash does integer division. It answers: how many whole times does it fit? And throws the fraction away. The leftover part is what the percent sign gives you: the remainder, or modulus operator. Together they split a number exactly. Seventeen is five times three, plus two. The remainder is handy. n remainder 2 is 0 for even numbers and 1 for odd ones. Minutes remainder 60 gives what's left after whole hours. Two traps. Seven divided by two gives three, with no warning; write 7.0 to get 3.5. And dividing a whole number by zero has no answer. C promises nothing, so check a divisor first.

Common Error

The Remainder Rejects Decimals

The remainder operator works only on whole numbers. Give it a decimal, as in 17.5 remainder 5, and the build stops. Clang says: invalid operands to binary expression, a double and an int. GCC words the same error differently.

Quick Check

135 Minutes in Hours and Minutes

Quick check. A game session lasted 135 minutes. This program turns that into hours and minutes. What does it print? Pause and predict. It prints 2 h 15 min. Sixty fits into 135 twice, and integer division throws the rest away, so hours is 2. What doesn't fit is 135 minus 120: 15. Nothing rounds up, and 25 would come from reading 2.25 hours as minutes.

Negative Numbers

Truncating Toward Zero

What about minus seven divided by two? The true answer is minus 3.5. There are two sensible ways to make it whole: down to minus four, or toward zero. Since C99, and so in C17, the rule is fixed. Integer division truncates toward zero: it just drops the fraction. The remainder is whatever makes the division add back up. So it takes the sign of the left number. A real run shows every combination. Minus seven divided by two is minus three, and the remainder is minus one, because minus three times two, minus one, is minus seven.

Precedence

Multiply Before You Add

Now, what is two plus three times four? Left to right gives twenty. A math teacher says fourteen, and C agrees with the teacher. Each operator has a precedence: a rank that decides which runs first. Parentheses come first, innermost first. Then a minus or plus in front of a single value, as in minus five. Then multiply, divide and remainder, all on one rank. Then add and subtract. Comparisons, the logical operators, and assignment come later. Assignment runs last of all.

Associativity

Equal Ranks Go Left to Right

What if two operators share a rank, as in ten minus four minus three? Then associativity decides. Arithmetic operators of the same rank go left to right, like reading a sentence. So it's ten minus four, then minus three: three. Run several cases at once. Ten minus four minus three is 3, but with parentheses around four minus three, it's 9. A hundred divided by ten, divided by five, is 2. Group the ten and five, and it's 50. The longest line: remainder and times share a rank, so left to right. Six remainder four is two, times three is six, and twenty minus six is fourteen. And in minus two times three, the minus binds to the two first. The double percent inside the string prints one percent sign; lesson 3.5 explains.

Parentheses

Fixing the Average of 80 and 91

Parentheses to the rescue. Priya wants the average of Sam's two rounds, 80 and 91. Without parentheses, the divide runs first: ninety-one divided by two is forty-five, and eighty plus forty-five gives a nonsense 125. With parentheses, the adding happens first: 171 divided by 2 is 85. Still not 85.5, because integer division drops the fraction. Divide by 2.0 instead, and the answer is 85.5. Parentheses fix the order; a decimal fixes the fraction.

Quick Check

A Bonus Rule Missing Parentheses

Quick check. Priya writes a bonus rule for the arcade. Sam plays at level 3 with 10 tokens. What bonus does the program print? Pause and predict. It prints twenty-five. Multiply outranks add, so five times three runs first, fifteen, and then ten is added. Sam expected forty-five, ten plus five, times three. That was Priya's real rule, and it needs parentheses around tokens plus five. Compile again, and the build is quiet. Run it, and it prints forty-five. Sam's test passes.

Key Takeaways

Division, Remainder and Order

To recap. With two whole numbers, slash gives the whole groups and percent gives what's left; together they rebuild the number. Division truncates toward zero, and the remainder takes the left number's sign. Higher precedence runs first, equal ranks go left to right, and parentheses override both. When in doubt, add them.

About Programming in C at UPI Study

Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Computing with Operators: Precedence and Associativity

What does the % operator do in C?
The % operator gives the remainder after whole-number division, so 17 % 5 is 2. Together with integer division it splits a number exactly: 17 is 5 times 3, plus 2. It is handy for tests such as n % 2, which is 0 for even numbers, and for leftovers such as minutes % 60. In C, % works only with integers, so 17.5 % 5 is a compile error.
What is -7 / 2 in C?
In C, -7 / 2 is -3, because integer division truncates toward zero, dropping the fraction from -3.5. This rule has been fixed since C99. The remainder, -7 % 2, is -1, because the remainder takes the sign of the left operand so that (-7 / 2) * 2 + (-7 % 2) equals -7. Rounding down to -4 would be the other possible choice, but C does not use it.
What is operator precedence in C?
Operator precedence is the rank that decides which operation runs first. In C, parentheses come first, then a unary plus or minus, then *, / and %, then + and -. Comparisons, logical operators and assignment rank lower still. So 2 + 3 * 4 is 14, not 20. To make an addition happen first, as in (tokens + 5) * 3, put it in parentheses.
What is associativity in C, with an example?
Associativity decides the order when operators of the same precedence meet. Arithmetic operators group left to right, so 10 - 4 - 3 is (10 - 4) - 3, which is 3, while 10 - (4 - 3) is 9. Likewise 100 / 10 / 5 is 2. In 20 - 6 % 4 * 3, % and * share a rank, so 6 % 4 gives 2, times 3 gives 6, and 20 - 6 is 14.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →