Variables and operators
Declare typed variables, print them with format specifiers, and see how integer arithmetic and overflow behave.
- Declare an int, double and char and print each with the right specifier.
- Explain that a type controls size and how bits are interpreted.
- Predict the result of integer division and the remainder operator.
- Describe what happens when an unsigned value overflows.
In plain English
A variable is a named box in memory that stores a value. Memory is the working storage of a running program, and compilation is the step that turns your C source file into a program the computer can run. A type tells the compiler how many bytes a variable uses and how to interpret them: int holds a whole number, double holds a decimal, and char holds one character. printf prints values by matching each format specifier such as %d, %f and %c to an argument. Integer division drops the fractional part instead of rounding, and when an unsigned integer grows past its largest value it wraps around to zero in a predictable way.
Step by step
- 1Declare an int and print it with %d.
- 2Add a double and print it with %.2f.
- 3Add a char and print it with %c.
- 4Print 7 / 2 and 7 % 2 and notice the remainder.
- 5Print UINT_MAX and UINT_MAX + 1 to watch an unsigned value wrap.
#include <stdio.h>
#include <limits.h>
int main(void) {
int count = 7;
double price = 19.99;
char grade = 'A';
printf("count = %d\n", count);
printf("price = %.2f\n", price);
printf("grade = %c\n", grade);
printf("7 / 2 = %d\n", 7 / 2);
printf("7 %% 2 = %d\n", 7 % 2);
unsigned int big = UINT_MAX;
printf("UINT_MAX = %u\n", big);
printf("UINT_MAX + 1 = %u\n", big + 1);
return 0;
}Common mistakes
- Using %d for a double makes printf read the wrong number of bytes and print garbage.
- Expecting 7 / 2 to be 3.5 is wrong, because integer division truncates toward zero.
- Forgetting the format specifier and printing a raw variable passes the value where printf expects a string.
- Assuming a signed integer that overflows wraps neatly is wrong, because signed overflow is undefined behaviour.
Average with integer division
Print the integer average of 20 divided by 3, then print the remainder of the same division on the next line.
int total = 20;
int lessons = 3;
printf("average = TODO\n");In C, what is the value of the expression 7 / 2?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.