Foundations · Module 0 · Lesson 2 of 3
Variables, Assignment, and Basic Expressions
Learn what a variable is, how to declare and assign int, float, double, and char values, and how to build arithmetic expressions and print results.
By the end you can
- Explain what a variable is and how it stores a value in memory
- Declare and initialize variables of type int, float, double, and char
- Write assignment statements and arithmetic expressions with +, -, *, /, and %
- Print variable values with printf and the correct format specifiers
01 · A question first
You can store a number in a variable, change it, and use it in a calculation. But if you write int age; age = 21; and then printf("%d", age) without understanding what the variable actually holds, you cannot predict what your program will print. What exactly is a variable, and where does its value live?
Make a guess, then step through the trace below to check it.
02 · Watch it run
int age = 21;float price = 9.99f;double total = price * 2;char grade = 'A';- variable 0age: 21 (int)(looked at in this step)
- variable 1price: 9.99 (float)
- variable 2total: uninitialized
- variable 3grade: uninitialized
Four variables are declared and initialized. Each occupies its own location in memory with its own type.
Machine work: allocate age, price, total, grade on stack
03 · The idea
Start with the problem
Suppose you are writing a program to calculate the total price of two identical items, each costing $9.99. You might be tempted to write:
printf("Total: 19.98\n");This works for one calculation, but it is not a program — it is just a hard-coded sentence. If the price changes to $12.50, you must edit and recompile the text itself.
A real program stores values in variables, performs calculations on those variables, and prints the results. That way, changing one number updates every calculation that depends on it. This lesson teaches you what variables are, how to create them, and how to combine them with arithmetic.
What is a variable?
Think of your computer's memory as a long row of numbered storage slots, like mailboxes at a post office. Each slot holds a piece of data.
A variable is a name you give to one of those storage slots, together with a type that tells the compiler what kind of data the slot holds and how much space it needs. When you write:
int age = 21;you are telling the compiler:
- Reserve a slot in memory large enough for an
int(whole number). - Call that slot
age. - Store the value
21in it.
From then on, whenever you write age in your code, the compiler substitutes the contents of that slot. If you later change the slot to 22, every use of age reflects the new value. This is why variables are powerful: they let you write general calculations that work for many different inputs.
Declaring and initializing variables
In C, you usually declare a variable before using it. A declaration states the type and the name:
int age; /* declares age; it holds an unpredictable value until assigned */
float price; /* declares price; holds a decimal number */
double total; /* declares total; holds a more precise decimal number */
char grade; /* declares grade; holds a single character */It is best practice to initialize a variable at the same time you declare it, giving it a known starting value:
int age = 21;
float price = 9.99f;
double total = 0.0;
char grade = 'A';Notes on syntax:
int— whole numbers, such as21,-5,0,1000.float— decimal numbers with single precision, such as9.99. Thefsuffix makes the literal afloatrather than adouble.double— decimal numbers with double (higher) precision, such as19.98. Usedoublefor most decimal work.char— a single character, written in single quotes, such as'A','7','?'. Internally it is stored as a number (its character code).- Every declaration ends with a semicolon.
- C is case-sensitive:
age,Age, andAGEare three different variables.
Naming variables
Use snake_case for variable names: write lowercase words separated by underscores. Choose a name that describes what the value means instead of using a vague name such as x or data.
int item_count = 5;
float unit_price = 9.99f;
char initial = 'J';Follow these rules:
- Start with a lowercase letter, then use lowercase letters, digits, and underscores.
- Use names such as
item_countandunit_pricerather thanitemCountorprice1. - Do not start a name with a digit, and do not use a C keyword such as
int,return, orwhile. - Keep names readable and specific;
remaining_minutesis clearer thanrm.
The assignment statement
Assignment copies a value into a variable using the = operator:
age = 22; /* stores 22 into age, overwriting 21 */
price = 12.50f; /* stores 12.50 into price */Important: = in C is assignment, not mathematical equality. It means "take the value on the right and store it into the variable on the left." So this is valid:
int count = 5;
count = count + 1; /* count is now 6 */Read count = count + 1 as: "take the current value of count, add 1, and store the result back into count." It would be meaningless in algebra, but it is one of the most common patterns in programming.
Arithmetic expressions
C supports the standard arithmetic operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 6 * 7 | 42 |
/ | Division | 10 / 2 | 5 |
% | Remainder (modulo) | 10 % 3 | 1 |
Two details trip up nearly every beginner:
Integer division truncates
When both operands of / are integers, C performs integer division: the result is an integer and any remainder is discarded.
int a = 7;
int b = 2;
int c = a / b; /* c is 3, not 3.5 */The fractional part .5 is thrown away. To get a true decimal result, at least one operand must be floating-point:
double c = 7.0 / 2; /* c is 3.5 */The modulo operator %
The % operator gives the remainder after integer division. It only works with integers.
int minutes = 125;
int hours = minutes / 60; /* 2 */
int leftover = minutes % 60; /* 5 */This is useful for questions like "how many full hours and remaining minutes?" or "is a number even or odd?" (n % 2 == 0 means even).
Printing variable values
You already know printf prints fixed text. To print a variable, you include a format specifier in the string and pass the variable as an additional argument:
int age = 21;
printf("Age: %d\n", age);| Specifier | Use for | Example |
|---|---|---|
%d | int (whole number) | printf("%d", age); |
%f | float or double (decimal) | printf("%f", price); |
%c | char (single character) | printf("%c", grade); |
The %d is a placeholder; printf replaces it with the value of age. You can have several placeholders:
int age = 21;
float price = 9.99f;
printf("Age: %d, Price: %f\n", age, price);The order matters: the first %d matches the first variable after the string (age), the second %f matches the second (price).
A complete example
Here is a small program that calculates the total price of two items and prints the result:
#include <stdio.h>
int main(void) {
float item_price = 9.99f;
int quantity = 2;
float total = item_price * quantity;
printf("Item price: %f\n", item_price);
printf("Quantity: %d\n", quantity);
printf("Total: %f\n", total);
return 0;
}Compile and run it:
gcc total.c -o total
./totalOutput:
Item price: 9.990000
Quantity: 2
Total: 19.980000The program reads item_price and quantity from variables, multiplies them, stores the result in total, and prints all three. If you change quantity to 3 and recompile, the total updates automatically — that is the power of variables.
Common beginner mistakes
| Mistake | What goes wrong | Fix |
|---|---|---|
| Using a variable before assigning it | Prints garbage or unpredictable value | Initialize when declaring |
printf("%d", price) with a float | Wrong output or a warning | Use %f for floats |
int result = 7 / 2; expecting 3.5 | Integer division gives 3 | Use 7.0 / 2 |
char grade = A; (no quotes) | Compiler treats A as an undefined variable | Use 'A' |
Forgetting #include <stdio.h> | Compiler does not know printf | Add the include |
Where it is used
Variables and expressions are the foundation of every program ever written. A game stores the player's score in a variable and updates it with an expression. A thermostat stores the current temperature in a variable and compares it to a target. A bank program stores balances in variables and adds deposits with +. Everything you build later in this track — arrays, structs, pointers, file I/O — is built on the simple idea of naming a memory slot and changing its value.
In the next lesson, you will learn how to read input from a person at the keyboard using scanf, so your programs can respond to different data each time they run.
04 · Prove it
Question 1 of 3 · answer from memory
Which line declares an integer variable named age and gives it the value 21?
05 · Practice
Asked in interviews
Something wrong with this lesson? Report a problem