Week 2: Getting Started in C¶
Agenda¶
- Structure of a C Program (review)
- Variables & Data Types
- Statements & Expressions
- Console I/O:
printfandfscanf - Conditionals
- Loops
Part 1¶
Structure of a C Program¶
The Minimal C Program¶
#include <stdio.h>— preprocessor directive; pulls in the Standard I/O libraryint main(void)— program entry point; OS calls this functionreturn 0;— signals successful execution to the OS
Anatomy: Preprocessor → Compiler → Linker¶
Source (.c)
│
▼ preprocessor (cpp)
Expanded Source
│
▼ compiler (gcc)
Object File (.o)
│
▼ linker (ld)
Executable (a.out)
The compiler only sees a single translation unit at a time.
The linker stitches multiple .o files and libraries together.
Your First Compile¶
| Flag | Meaning |
|---|---|
-Wall |
Enable common warnings |
-Wextra |
Enable extra warnings |
-std=c17 |
Target C17 standard |
-o hello |
Name the output binary |
Treat warnings as errors during development. Use
-Werrorfor zero tolerance.
Part 2¶
Variables & Data Types¶
Declaring Variables¶
- In C, you must tell the compiler about the variables you are going to use and their type before you use them.
- Contrast with Python, which is dynamically typed:
Fundamental Types¶
| Type | Typical Size | Range (signed) | Format Specifier |
|---|---|---|---|
char |
1 byte | −128 to 127 | %c / %d |
int |
4 bytes | −2,147,483,648 to 2,147,483,647 | %d |
float |
4 bytes | ~6–7 decimal digits | %f |
double |
8 bytes | ~15–16 decimal digits | %lf |
Sizes are implementation-defined. Use
sizeofto be sure.
sizeof Operator¶
#include <stdio.h>
int main(void) {
printf("char: %zu bytes\n", sizeof(char));
printf("int: %zu bytes\n", sizeof(int));
printf("float: %zu bytes\n", sizeof(float));
printf("double: %zu bytes\n", sizeof(double));
return 0;
}
sizeof returns a value of type size_t — use %zu to print it.
unsigned and Type Modifiers¶
unsigned int score = 0; // 0 to 4,294,967,295
short int s = 10; // typically 2 bytes
long int big = 1000000L;
long long huge = 9000000000LL;
- Dropping the sign bit doubles the positive range
- Use
unsignedfor things that can’t be negative (sizes, counts)
Integer Division — A Classic Trap¶
When both operands are integers, / performs integer (truncating) division.
double result = (double)a / b; // 3.5 ✓
double wrong = (double)(a / b); // 3.0 ✗ — cast happens too late
Type Mixing & Implicit Conversion¶
C promotes types automatically in mixed expressions:
Rule of thumb: the “wider” type wins in arithmetic.
Explicit Type Casting¶
Casting syntax: (type) expression
Use casts to:
- Force floating-point division from integer operands
- Narrow a wider type (be careful — data loss possible)
- Pass the right type to functions expecting a specific type
Variable Declaration & Initialization¶
int health = 100; // initialize at declaration — always!
float speed = 3.14f; // f suffix → float literal (not double)
char grade = 'A'; // single quotes for char literals
double pi = 3.14159265358979;
int x; // uninitialized — undefined behavior to read!
Best practice: initialize every variable at the point of declaration.
Part 3¶
Statements & Expressions¶
Expressions vs. Statements¶
| Concept | Definition | Example |
|---|---|---|
| Expression | Produces a value | 3 + 4, x * y, a > b |
| Statement | Performs an action | x = 5;, return 0; |
| Expression statement | Expression + semicolon | printf("hi\n"); |
Every expression has a type and a value.
Arithmetic Operators¶
| Operator | Operation | Example | Result |
|---|---|---|---|
+ |
Addition | 3 + 4 |
7 |
- |
Subtraction | 10 - 3 |
7 |
* |
Multiplication | 3 * 4 |
12 |
/ |
Division | 7 / 2 |
3 |
% |
Modulo (remainder) | 7 % 2 |
1 |
Order of Operations (Precedence)¶
C follows standard mathematical precedence:
Highest: () — grouping / function call
* / % — multiplicative
+ - — additive
Lowest: = — assignment (right-to-left)
When in doubt, add parentheses for clarity.
Compound Assignment & Increment¶
x += 5; // x = x + 5
x -= 2; // x = x - 2
x *= 3; // x = x * 3
x /= 4; // x = x / 4
x %= 7; // x = x % 7
x++; // post-increment: use x, then add 1
++x; // pre-increment: add 1, then use x
x--; // post-decrement
Part 4¶
Console Input & Output¶
printf — Formatted Output¶
#include <stdio.h>
int main(void) {
int level = 5;
double health = 87.5;
char grade = 'B';
printf("Level: %d\n", level);
printf("Health: %.1f` | — | Literal `%` character |
| `%p` | pointer | Memory address |
---
## `scanf` — The Problem
```c
scanf("%d", &age); // Works — but has issues:
- Leaves
\nin the input buffer - Next
scanfcall for acharor string reads that leftover newline - Leads to confusing, hard-to-debug input behavior
- Prone to bugs like buffer overflow!
fscanf with Newline Stripping¶
The fix: consume the newline explicitly.
#include <stdio.h>
int main(void) {
int age;
char initial;
fscanf(stdin, "%d ", &age); // trailing space eats whitespace/newline
fscanf(stdin, "%c", &initial); // now reads the real character
printf("Age: %d, Initial: %c\n", age, initial);
return 0;
}
The space before
%cin a format string skips all leading whitespace including\n.
Reading Strings Safely¶
%63sreads at most 63 characters (leaves room for\0)- Never use
%swithout a width limit on untrusted input
Part 5¶
Conditionals¶
What is “True” in C?¶
C has no dedicated boolean type in C89/90.
(C99 introduced _Bool / <stdbool.h>)
| Value | Boolean meaning |
|---|---|
0 |
False |
| Anything else | True |
int x = 42;
if (x) printf("true!\n"); // prints — 42 ≠ 0
if (0) printf("never\n"); // never prints
if (-1) printf("true!\n"); // prints — nonzero
The if Statement¶
Comparison & Logical Operators¶
| Operator | Meaning |
|---|---|
== |
Equal to |
!= |
Not equal to |
< > |
Less / greater than |
<= >= |
Less / greater than or equal |
&& |
Logical AND |
\|\| |
Logical OR |
! |
Logical NOT |
Common bug:
=(assignment) vs==(comparison)
if / else / else if¶
int score = 82;
if (score >= 90) {
printf("A\n");
} else if (score >= 80) {
printf("B\n");
} else if (score >= 70) {
printf("C\n");
} else if (score >= 60) {
printf("D\n");
} else {
printf("F\n");
}
Conditions are evaluated top to bottom; first match wins.
switch / case¶
char grade = 'B';
switch (grade) {
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Good job!\n");
break;
case 'C':
printf("Passing.\n");
break;
default:
printf("See advisor.\n");
break;
}
- Works on integer types and
charonly breakis required to prevent fall-throughdefaulthandles unmatched values
Fall-Through: Intentional vs. Accidental¶
// Intentional fall-through (document it!)
// 0: Sunday, 7: Saturday
switch (day) {
case 6: /* FALL THROUGH */
case 0:
printf("Weekend!\n");
break;
default:
printf("Weekday\n");
break;
}
Forgetting break is one of the most common C bugs.
Part 6¶
Loops¶
The for Loop¶
Best for: loops with a known iteration count.
for Loop Mechanics¶
┌─────────────────────────────────────┐
│ int i = 0 ← runs ONCE │
│ │ │
│ ▼ │
│ i < 5 ? ──No──→ exit loop │
│ │ Yes │
│ ▼ │
│ execute body │
│ │ │
│ ▼ │
│ i++ ← runs each iter │
│ │ │
│ └──────────────────────────────┘
The while Loop¶
Best for: loops where the exit condition is dynamic.
May execute zero times if condition is false initially.
The do…while Loop¶
int choice;
do {
printf("Enter 1–4: ");
fscanf(stdin, "%d", &choice);
} while (choice < 1 || choice > 4);
Guaranteed to execute at least once.
Perfect for input validation menus.
break and continue¶
for (int i = 0; i < 10; i++) {
if (i == 3) continue; // skip iteration when i == 3
if (i == 7) break; // exit loop entirely when i == 7
printf("%d ", i);
}
// Output: 0 1 2 4 5 6
| Keyword | Effect |
|---|---|
break |
Immediately exits the innermost loop (or switch) |
continue |
Skips the rest of the current iteration |
Nested Loops¶
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
printf("[%d,%d] ", row, col);
}
printf("\n");
}
break/continue affect only the innermost loop.
Week 2 Wrap-Up¶
Key Takeaways¶
- Every C program starts at
main(); every statement ends with; - Know your types — integer division truncates
- Use
(double)casts before division when you need precision printfformat specifiers must match the argument type- Use
fscanf(stdin, "%d ", &x)with trailing space to strip newlines - In C, zero is false, everything else is true
- Match the loop form to the use case:
for/while/do-while
Looking Ahead — Week 2 Lab¶
You will practice today’s concepts hands-on:
- Type sizing exploration with
sizeof - Integer vs. float division experiments
- Building a formatted output table with
printf - Writing an input-validated menu loop
- Grade calculator using conditionals
See you in lab!
Resources¶
- The C Programming Language — Kernighan & Ritchie (K&R), 2nd Ed.
- C Programming: A Modern Approach — K.N. King
man 3 printf— POSIX printf reference- https://en.cppreference.com/w/c — C language reference
Created : May 18, 2026