Chapter 2: Variables, Data Types, and Operators

In the previous chapter, we successfully ran our first program. Now, we need to learn how to store and manipulate data. Unlike Python, where you can simply assign a value to a name, C requires you to explicitly declare the "data type" of every variable you use. This is called static typing, and it is a key reason why C programs are so fast.

1. Declaring Variables

To declare a variable, you state the data type followed by the variable name. If you try to put a decimal number into an integer variable, C will either truncate the decimal or throw an error depending on the compiler.

int age = 25;
float height = 5.9;
char initial = 'A';

2. Essential Data Types

3. Operators

Operators perform operations on variables and values. C includes:

4. Printing Variables with Format Specifiers

To print variables in C, you must use "format specifiers" inside printf. These tell C what kind of data to expect:

printf("Age: %d", age);      // %d for int
printf("Height: %.2f", height); // %.2f for float (2 decimals)
printf("Initial: %c", initial); // %c for char

Common Beginner Mistakes

Try It Yourself

  1. Declare an integer for your age and a float for your height.
  2. Perform a simple calculation (e.g., age + 5) and store it in a new variable.
  3. Print both the original variables and the result using printf.

Type Casting in C

C is strict about data types, so mixing them often requires an explicit cast. This is especially important with division, where two integers will produce an integer result unless you cast one to a float.

int a = 7, b = 2;
printf("%d\n", a / b);              // prints 3
printf("%f\n", (float)a / b);       // prints 3.500000

Operator Precedence

Just like in math, C operators follow a strict order of evaluation — multiplication and division happen before addition and subtraction. When in doubt, use parentheses to make your intent explicit and avoid subtle bugs.

int result = 2 + 3 * 4;      // 14, not 20
int clearer = 2 + (3 * 4);   // also 14, but easier to read