TRT
Sign in

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.

FreeAbout 15 minutes

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

Builds on Installing a Compiler and Your First C Program.

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

Declaring variables, assigning values, and evaluating an expressionstep 1 of 3
int age = 21;float price = 9.99f;double total = price * 2;char grade = 'A';
  1. variable 0age: 21 (int)(looked at in this step)
  2. variable 1price: 9.99 (float)
  3. variable 2total: uninitialized
  4. 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:

c
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:

c
int age = 21;

you are telling the compiler:

  1. Reserve a slot in memory large enough for an int (whole number).
  2. Call that slot age.
  3. Store the value 21 in 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:

c
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:

c
int age = 21;
float price = 9.99f;
double total = 0.0;
char grade = 'A';

Notes on syntax:

  • int — whole numbers, such as 21, -5, 0, 1000.
  • float — decimal numbers with single precision, such as 9.99. The f suffix makes the literal a float rather than a double.
  • double — decimal numbers with double (higher) precision, such as 19.98. Use double for 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, and AGE are 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.

c
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_count and unit_price rather than itemCount or price1.
  • Do not start a name with a digit, and do not use a C keyword such as int, return, or while.
  • Keep names readable and specific; remaining_minutes is clearer than rm.

The assignment statement

Assignment copies a value into a variable using the = operator:

c
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:

c
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:

OperatorMeaningExampleResult
+Addition5 + 38
-Subtraction10 - 46
*Multiplication6 * 742
/Division10 / 25
%Remainder (modulo)10 % 31

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.

c
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:

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

c
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:

c
int age = 21;
printf("Age: %d\n", age);
SpecifierUse forExample
%dint (whole number)printf("%d", age);
%ffloat or double (decimal)printf("%f", price);
%cchar (single character)printf("%c", grade);

The %d is a placeholder; printf replaces it with the value of age. You can have several placeholders:

c
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:

c
#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:

bash
gcc total.c -o total
./total

Output:

text
Item price: 9.990000
Quantity: 2
Total: 19.980000

The 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

MistakeWhat goes wrongFix
Using a variable before assigning itPrints garbage or unpredictable valueInitialize when declaring
printf("%d", price) with a floatWrong output or a warningUse %f for floats
int result = 7 / 2; expecting 3.5Integer division gives 3Use 7.0 / 2
char grade = A; (no quotes)Compiler treats A as an undefined variableUse 'A'
Forgetting #include <stdio.h>Compiler does not know printfAdd 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

Something wrong with this lesson? Report a problem

Not started

Sign in to save your learning progress.

Sign in to save