UPI Study › Courses › C++ Programming › Free lessons › Lesson 2.8 Free with a free account
Number Crunching in Code
C++ Programming · Chapter 2: Getting Started with C++Section 2.8 · lesson 15 of 84video coming soon
← Your First C++ Output ProgramNext lesson: Procedure-Driven vs. Object-Driven →
In this lesson
Operators, precedence, and arithmetic expressions.
- Use the five arithmetic operators
- Predict when division discards a fraction
- Evaluate expressions by precedence and associativity
- Mix types safely, with casts where needed
Transcript
Everything said in the video, section by section (1,512 words). Read along, or search it.
Opening Puzzle
Five Divided By Two Gives Two
In school, five divided by two is two and a half. Ask C++, and it says two. Arithmetic in code looks exactly like the arithmetic you already know, and that's the difficulty. It agrees almost everywhere. And in the few places where it doesn't, it gives no warning. It simply produces a confident, wrong answer. This lesson is about those places: integer division, precedence, the increment operators, mixed types, and the approximate nature of fractions.
Operators
The Five Arithmetic Operators
There are five arithmetic operators, and four are entirely familiar. Plus is addition. Minus is subtraction, and it also negates a single value. Star is multiplication, and it's never implied. Two x isn't multiplication: you must write two, star, x. Slash is division, which behaves differently on whole numbers, as we'll see next. And percent is the remainder: what's left over after whole-number division. Seven remainder three is one. It works on whole-number types only. It's more useful than it looks. N remainder two tells you whether n is even. Seconds remainder sixty gives the leftover seconds. And index remainder size wraps a counter back to zero.
Key Rule
Whole Numbers Discard the Fraction
Here's the rule that catches nearly everyone once. If both sides of a division are whole numbers, C++ does whole-number division, and the fraction is discarded. Not rounded. Discarded. So five divided by two is two. And there's no warning, because from the language's point of view, nothing went wrong. You asked two integers to be divided, and integers can't represent a half. The moment either side has a fractional type, the whole operation becomes fractional division. Five point oh over two widens the two to two point oh, and gives two point five. So the operands decide the arithmetic. What you plan to do with the answer afterward has no influence at all.
Worked Examples
Division, Remainder, and Division by Zero
Here's division and remainder, worked through. Minus seven divided by two is minus three. The fraction is dropped toward zero, not downward, so it's not minus four. One divided by two, times ten, is zero. Left to right: one over two is zero first, and zero times anything is zero. But ten times one, divided by two, is five, because the multiplication happens before the fraction can be lost. Minus seven remainder three is minus one. The remainder takes the sign of the left-hand operand. And seven point oh remainder three won't compile. One more danger. Whole-number division by zero isn't defined: the program may crash, or do anything. The compiler can't catch it, so guard any divisor that comes from input.
Common Mistake
The Average That Comes Out Low
This rule causes one bug, almost word for word, in nearly every beginner's code. A program adds three scores in an int, 253, and divides by an int count of three, to get an average. The true average is eighty-four point three three. The program gets eighty-four. Every average comes out slightly low, and always whole. And declaring the result as a double doesn't help. The fraction is thrown away during the division, before anything is stored. The arithmetic is correct. The types are wrong. We'll fix it shortly.
Grouping Rules
Precedence and Associativity Explained
When an expression has more than one operator, two rules decide how it groups. Precedence settles which operator binds more tightly: multiplication before addition, as in mathematics. Associativity settles operators of equal precedence. Parentheses come first, innermost outward. Then postfix increment and decrement. Then prefix increment, negation and casts, which group right to left. Then star, slash and percent, left to right. So one hundred over ten over two is five, not twenty. Then plus and minus, left to right. So ten minus four minus three is three, not nine. And assignment binds loosest of these, right to left. That's why an assignment can hold a whole calculation on its right: everything else finishes first.
Step by Step
Collapsing One Expression Operator by Operator
Here's one expression, collapsed one operator at a time: two plus three times four, minus ten over five. The highest level present is times and divide. Same level, so left to right: three times four is twelve. Then ten over five is two. Now plus and minus, again left to right. Two plus twelve is fourteen, and fourteen minus two is twelve. Parentheses override all of it. Two plus three times four is fourteen, but two plus three, in parentheses, times four, is twenty. So adopt this rule for good: if you had to stop and check the precedence table, add the parentheses. They cost nothing at run time.
Quick Check
Two Traps in One Line
Quick check. Evaluate twenty minus six over three times two, the way C++ would. Then, what changes if you put parentheses around twenty minus six? Pause and work it out. Without parentheses: six over three is two, two times two is four, and twenty minus four is sixteen. With them: twenty minus six is fourteen. Fourteen over three is four, because that's integer division. And four times two is eight. Two traps in one line: precedence, and the lost fraction.
Shorthand
Compound Assignment Operators
Adjusting a variable using its own value is so common that there's a shorthand for it. Total plus equals five means total equals total plus five: a running sum. Minus equals reduces a quantity, and times equals scales one. Divide equals halves, but remember the whole-number rule. And remainder equals wraps a counter back to the start. Beyond brevity, the shorthand names the variable once, so there's no chance of a slightly different name on the right, a slip that's remarkably hard to spot. And the whole right side is worked out first. Total times equals two plus three multiplies total by five, not by two.
Increment Operators
Prefix Versus Postfix Return Values
Adding or subtracting exactly one has its own operators: plus plus adds one, and minus minus subtracts one. Both can go before the variable or after it. Either way the variable changes by one. What differs is the value the expression hands back. Prefix changes first, then hands back. Starting from a equals five, b equals plus plus a makes a six, and b six. Postfix hands back first, then changes. B equals a plus plus gives b five, the old value, and then a becomes six. If nothing uses the result, like a plus plus on a line of its own, the two forms behave identically. So keep them on lines of their own. And never change a variable while also reading it elsewhere in the same expression, like b equals a plus plus, times a. That's undefined behavior, and compilers may disagree.
Mixed Types
The Type Conversion Ladder
An operator needs both operands to be the same type. When they aren't, the compiler converts one first. It converts the narrower operand up to the wider type, so no fraction is lost. The result has the wider type. The ladder runs from char, to int, to long, to float, to double. Lower rungs have less room, and no fractions. Higher rungs have more room, and hold fractions. Going up is automatic, and almost always safe. Going down is the dangerous direction. It happens when you store a wide value into a narrow variable: two point nine into an int gives two. Clang warns about that one. Warnings like it are worth reading, rather than silencing.
The Fix
Casting Before the Division
When the automatic rules aren't what you want, a cast states the conversion explicitly. The C++ form is static cast, naming the target type and the value. Back to the average. Total over count is still wrong: both are whole numbers, so the fraction is lost before storing. Static cast to double of total, divided by count, is correct and preferred. One operand is now fractional, so count is widened, and the fraction is kept. The older C form, double in parentheses, works too. And with a literal, writing three point oh instead of three is the smallest fix. But notice where the cast goes. Static cast of total over count, all together, is too late. The division already lost the fraction, and the cast faithfully widens the wrong answer.
Precision Limits
Why Fractions Are Only Approximate
One more surprise, and it isn't a defect in C++. It's true of essentially every language and machine. Fractional numbers are stored in binary, in a fixed amount of room, and most decimal fractions have no exact binary form. Zero point one is one of them. So zero point one plus zero point two prints as zero point three, but it isn't equal to zero point three. Add zero point one a thousand times, and the errors accumulate: the total drifts away from one hundred. So hold money as a whole number of cents, and compare fractional values within a small tolerance, never for exact equality. Neither type is flawed. Whole-number types are exact, but can't hold fractions. Fractional types hold fractions, but aren't exact.
Key Takeaways
Summary of Arithmetic Pitfalls
To summarize. A whole number divided by a whole number discards the fraction, toward zero, with no warning. The operands decide the arithmetic. Times, divide and remainder bind before plus and minus, and equal levels run left to right. Prefix increment changes, then hands back. Postfix hands back, then changes. Keep them on their own lines. And to get a fractional result from whole numbers, widen an operand with static cast before dividing, not after. When in doubt, add parentheses.
About C++ Programming at UPI Study
C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. 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.
Enroll now → Course details Download the syllabus Every course with PRO →
Why take it here
Why students take C++ Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
C++ Programming 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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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 Number Crunching in Code
Why does 5 / 2 give 2 in C++ instead of 2.5?
How does C++ decide the order of evaluation in an expression like 20 - 6 / 3 * 2?
How do I get a decimal average from an int total and an int count in C++?
What does the % operator do in C++, and what are its limits?
About the C++ Programming course
How many college credits is C++ Programming?
How much does C++ Programming cost and what is included?
Which universities accept UPI Study credits?
How long does C++ Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in C++ Programming.
84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →