CS210 · Block 1 · Lesson 3

Operators and Standard Libraries

Arithmetic · Comparison · Precedence · Standard libraries · math.h · User input with scanf
At a glance: Now that you can declare variables, you make them do things. Today is arithmetic and comparison operators, the precedence rules that decide what gets evaluated first, your first taste of the C standard library through <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.
Contents
  1. Lesson Objectives
  2. Assigned Readings
  3. Pre-Class Work
  4. Lesson Materials and Overview
  5. In-Class Work
  6. After Class
1. Lesson Objectives

By the end of this lesson, cadets will be able to:

  1. Apply arithmetic and comparison operators in C expressions. (Outcome 1)
  2. Predict the result of expressions involving operator precedence and associativity. (Outcome 1)
  3. Locate and call functions from the C standard library, using <math.h> as an example. (Outcome 2)
  4. Read library reference documentation to understand a function's parameters, return value, and usage. (Outcome 7)
  5. Read numeric input from the user with scanf, using & before variable names as a required syntactic ritual until pointers are formally introduced in Lesson 12. (Outcomes 1, 2)
2. Assigned Readings

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
Heads up: The Beej website may be blocked on USAFA networks. If you cannot reach it from a campus connection, try from off-network or schedule EI to get a mirrored copy.
3. Pre-Class Work
Do this first
Plan on about 30 minutes for the reading and the Lesson 2 self-check. Most of today's learning happens through the two widgets in Section 5; come ready to type.

Pre-Class Checklist

1
Read Beej-C Chapter 3 (Variables and Statements: Operators) cont. — focus on operators and scanf
Focus on:
  • Arithmetic operators (+ - * / %)
  • Comparison operators (== != < > <= >=)
  • scanf for reading user input (skip &&, ||, and ! for now; those come in Lesson 4)
2
Make sure Lesson 2 still feels solid
Today builds on declarations, types, and overflow from Lesson 2. If any of those feel shaky, replay the Lesson 2 cmem or binary walkthroughs before class. If the trap (a value that does not fit in its type wraps to something unexpected) is not familiar, you will struggle with the arithmetic widget today.
3
Skim the In-Class section below
Section 5 has one widget: an arithmetic walkthrough that watches values change as you do arithmetic on them. You do not need to use it yet; just know it is there.
4. Lesson Materials and Overview

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.

Jump to
Slides scanf Arithmetic Comparison Precedence Libraries Reading Docs DFCS Standard

Slides

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.

Open Lesson 3 slides →

scanf for user input

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
%dintSame as printf.
%ffloatSame as printf.
%lfdoubleDifferent 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.
The & 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:

int n;
printf("Enter an integer: ");
scanf("%d", &n);
printf("You entered %d.\n", n);

Now a double:

double x;
printf("Enter a number: ");
scanf("%lf", &x);  // note %lf, not %f
printf("You entered %.2f.\n", x);

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).

Arithmetic operators

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.

int a = 5 / 2;
// a is 2, not 2.5

float b = (float)5 / 2;
// b is 2.5 -- cast one operand to float

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.

Comparison operators

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.

Classic bug. Writing 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.

Operator precedence and associativity

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.

Standard libraries

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:

$ gcc program.c -o program -lm
// ^^^ "link 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.

Reading library documentation

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:

  1. What header do I need to #include?
  2. What does the function take (parameters and their types)?
  3. What does it return (and what type)?
  4. What does it do on edge cases (negative inputs, zero, very large values)?

A typical reference page looks like this:

sqrt, sqrtf, sqrtl
Compute the square root

#include <math.h>

double sqrt(double x);

Description
Returns the non-negative square root of x. If x is negative, a domain
error occurs and the function returns NaN.

Return value
The square root of x.

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.

DFCS C Programming Standard

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.

  • §6.1 Whitespace around operators. Write 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.
  • §7.1 No magic numbers. When a constant has meaning (the 100 in 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.
  • §8.2 Don't trust input data. 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.

5. In-Class Work

Two things to do in class. Use the checklist to track your progress.

  • Work through the arithmetic walkthrough. Ten guided tasks: declare a variable, do arithmetic on it, watch overflow happen at the edge of the type. About 20 minutes.
  • Complete Lab 03: Compound Interest. Read three numbers from the user with scanf, apply arithmetic operators and pow from <math.h> to compute compound interest. Submitted through Gradescope. Full instructions in the lab repo.

Arithmetic & Overflow Walkthrough

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.

Before you begin

Enter your name. It will appear on the completion screen so you can include it in your screenshot for the Blackboard reflection quiz.

CS210 Lesson 3 · Arithmetic & Overflow Walkthrough

Declare typed variables, then do arithmetic on them. Watch values change byte by byte; watch overflow happen when a sum no longer fits.
Task 0 of 10
Section 1: Declare and add
Current task
Loading...
Memory & arithmetic
No variables yet.
Type a declaration on the left.
arith>
How this works: Type real C statements. A declaration like 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 += -= *= /= %=).
6. After Class
  • Finish Lab 03 if you did not complete it in class. Submit through Gradescope before Lesson 4.
  • Read Beej-C Chapter 3 (Variables and Statements: Flow Control, if) for Lesson 4. We will spend a full lesson on conditionals, truthiness vs Python, and the logical operators (&&, ||, !) that combine conditions.
  • Replay the arithmetic walkthrough. In free mode, try multiplications and divisions with edge values. Predict the wrap before you press Enter. Try mixing types (e.g., a short and an int) and see what happens.
  • Heads up: Quiz 1 at Lesson 4 covers Lessons 2 and 3 together. Variables, types, sizeof, overflow, arithmetic operators, comparison operators, precedence, math.h, scanf, and output formatting are all fair game.
Need help? Schedule EI with your instructor. Bring specific code or specific screenshots, and the exact error message or output you do not understand. Specific questions get unstuck quickly.