<math.h>, and your first way to get input from the user with scanf. The interactive widget in Section 5 watches what happens when arithmetic pushes a variable past its type's edge; the lab puts scanf, arithmetic, and math.h together in one small program.
By the end of this lesson, cadets will be able to:
<math.h> as an example. (Outcome 2)scanf, using & before variable names as a required syntactic ritual until pointers are formally introduced in Lesson 12. (Outcomes 1, 2)Complete before class. The first two are the spine of today's lecture; the King chapter is optional reinforcement.
| Source | Sections | Why |
|---|---|---|
| Beej-C | Chapter 3 (Variables and Statements: Operators) cont., including scanf coverage | Arithmetic and comparison operators (skip logical/bitwise for now); how scanf reads input |
| Beej-Lib | <math.h> reference page |
Skim the function index; we use it as a worked example of reading library docs |
| King, C Programming: A Modern Approach | Chapter 4 (Expressions) | Optional deeper dive on arithmetic operators and precedence |
+ - * / %)== != < > <= >=)scanf for reading user input (skip &&, ||, and ! for now; those come in Lesson 4)Lesson 2 gave you values; Lesson 3 makes you do things with them and start reading values from the user. The pieces below cover scanf for input, arithmetic and comparison operators (with their traps and precedence rules), and a first look at the C standard library through <math.h>. The reference material below previews the concepts you will see in lecture and exercise in the arithmetic walkthrough and the lab.
The Lesson 3 deck covers scanf and the & ritual, arithmetic and comparison operators, the precedence table, the integer division and = vs == traps, and a worked example of reading the <math.h> documentation. The slides are the spine of the in-class lecture; the arithmetic widget in Section 5 is where you practice.
Your programs so far have only computed values you hard-coded. scanf reads values from standard input (typed at the terminal, or piped in from a file) and stores them in variables. It is the input counterpart of printf.
Like printf, scanf uses format specifiers to decide how to interpret the input. The same specifiers you learned in Lesson 2 apply, with one important wrinkle for double:
| Specifier | For reading into | Notes |
|---|---|---|
| %d | int | Same as printf. |
| %f | float | Same as printf. |
| %lf | double | Different from printf. printf accepts %f for both float and double, but scanf requires %lf for double. Using %f for a double will silently store garbage. |
& ritual. Always put & before the variable name when reading into it. You will learn why in Lesson 12; for now, treat it as required syntax. Forgetting the & is one of the most common C bugs and the compiler will not stop you. Your program will compile, run, and quietly corrupt memory.
Two examples. First, read an int:
Now a double:
Return value. scanf returns the number of items it successfully read. For one variable, a successful read returns 1. You can ignore the return value for now, but production code checks it to catch input errors (the user typed letters when you asked for a number).
Five arithmetic operators: + addition, - subtraction, * multiplication, / division, and % modulo (remainder after division). The first three behave like you would expect from Python. The last two have a trap.
The integer division trap. In C, if both operands of / are integers, the result is an integer with the decimal part truncated. This is the same trap from Lesson 2's casting section; today it shows up everywhere arithmetic does.
The modulo operator. a % b gives you the remainder when a is divided by b. Together, / and % split an integer into its quotient and remainder, which is useful for things like extracting digits, checking divisibility, or implementing time conversions (seconds / 60 for minutes, seconds % 60 for leftover seconds).
Arithmetic overflow. In Lesson 2 you saw what happens when you store a too-big value in a too-small type. Today you will see the same effect through arithmetic: adding 1 to a variable at its type's maximum wraps it to the minimum; the compiler does not warn you. The arithmetic walkthrough in Section 5 makes this concrete.
Operator shorthands. x += 5 is the same as x = x + 5. Similar shorthands exist for -=, *=, /=, %=. x++ increments x by 1; x-- decrements. These shorthands save typing but do not change behavior or speed; use them when they read more clearly than the long form.
Six comparison operators that take two values and return either 0 (false) or 1 (true): ==, !=, <, >, <=, >=. Notice that equality is ==, not =. The single equals sign is assignment; the double equals sign is comparison.
x = 5 when you meant x == 5. The single-equals form is assignment: it stores 5 in x and produces the value 5. The double-equals form is comparison: it leaves x alone and produces either 0 or 1. The compiler will not error on a mix-up; some compilers warn under -Wall. Two defenses worth building as habits: write == for comparisons by reflex, and consider putting the constant on the left (5 == x) so a typo of = becomes a hard error the compiler must reject.
Truthiness in C. C does not have a separate boolean type at this level. Integers stand in for booleans directly: zero means false, anything else means true. Comparison operators always produce exactly 0 or 1. You will start using comparisons inside actual conditional statements in Lesson 4.
When an expression has multiple operators, precedence decides which ones get evaluated first. Higher rows bind tighter. The full table has 15+ tiers; these are the ones you need today.
| Tier | Operators | Associativity |
|---|---|---|
| 1 (tightest) | -x (unary minus) (type) ! (Lesson 4) | right to left |
| 2 | * / % | left to right |
| 3 | + - | left to right |
| 4 | < <= > >= | left to right |
| 5 | == != | left to right |
| 6 | && (Lesson 4) | left to right |
| 7 | || (Lesson 4) | left to right |
| 8 (loosest) | = += -= *= /= %= | right to left |
The key thing to internalize. Arithmetic binds tighter than comparison. So x + 1 > y * 2 is parsed as (x + 1) > (y * 2). Multiplication, division, and modulo also bind tighter than addition and subtraction, just like in math. Lesson 4 adds the logical operators (&&, ||, !) into the precedence mix; you can see where they sit in the table above for future reference.
When in doubt, parenthesize. The compiler does not care if you parenthesize an expression that did not need it. The next person reading your code (including future you) will thank you.
C ships with a small set of standard library headers that give you common functions: input/output, strings, math, memory, time, and a few more. You #include the header to make the functions visible, then call them like any other function.
Today's worked example is <math.h>. Common functions:
| Function | What it does |
|---|---|
| sqrt(x) | Square root of x. Returns NaN if x is negative. |
| pow(x, y) | x raised to the y power. |
| fabs(x) | Absolute value of x (for floating-point). |
| ceil(x), floor(x) | Round up / round down to the nearest integer. |
| round(x) | Round to nearest integer; ties round away from zero. |
The linker flag trap. When you compile a program that uses <math.h>, you need to tell the linker to include the math library:
If you forget -lm, you will see a confusing "undefined reference to sqrt" error at link time. The compiler found the prototype in the header, but the linker could not find the actual code. This is a category of error worth recognizing now; we will see it again with other libraries later in the course.
Real C development means reading reference docs constantly. You cannot memorize every function, and you do not need to. The skill is reading a doc entry and pulling out four things:
#include?A typical reference page looks like this:
From that page, you can read off: include <math.h>, takes a double, returns a double, returns NaN on negative input. That is enough to use the function correctly.
In class we will walk through three or four entries from Beej-Lib's <math.h> page together so you build the habit of reading docs rather than guessing.
Three sections of the DFCS C Programming Standard start landing today. Once introduced, they are course-wide rules and apply to every lab you write for the rest of CS210.
x + 1, not x+1. Write a == b, not a==b. The space between operators and operands makes expressions readable; the standard treats it as required.rate / 100 converts a percent to a fraction; the 9.81 in physics code is gravity), give it a name with #define or const. The next person reading your code should not have to guess what the literal means.scanf returns the number of values it successfully read. Production code checks that count and handles the mismatch case (bad input, end-of-file, etc). You will see this pattern in the reference solution to Lab 03 after grading. We revisit "don't trust input" at Lesson 12 with NULL checks and again at Lesson 37 in defensive programming.The full standard lives in the course Resources section. Keep it open in a tab while you write code.
Two things to do in class. Use the checklist to track your progress.
pow from <math.h> to compute compound interest. Submitted through Gradescope. Full instructions in the lab repo.
Ten tasks across four sections. Declare a variable, then type arithmetic expressions to update it. The right pane shows what gets stored and which bits flipped.
Enter your name. It will appear on the completion screen so you can include it in your screenshot for the Blackboard reflection quiz.
short s = 100; creates a variable. An assignment like s = s + 30; updates it; the compound form s += 30; does the same thing. The right pane shows the new bits and which ones flipped. Operators: + - * / % (and their compound forms += -= *= /= %=).
&&, ||, !) that combine conditions.short and an int) and see what happens.