Lesson 2 of 23

Variables and Format Specifiers

9 min 20 XP

In C you declare a variable's type first: int (whole number), float/double (decimal), char (one character). To print values, printf uses format specifiers: %d for int, %f for double, %c for char.

Example: edit me and press Run

Output Loading C (first time takes a few seconds)
Press Run to see the result here.

%.2f prints two decimal places. sizeof() tells you how many bytes a type uses. A const variable can't be changed.

Example: edit me and press Run

Output Loading C (first time takes a few seconds)
Press Run to see the result here.

Using the wrong specifier (like %f for an int) prints garbage. Interviewers do ask about format specifiers!

Challenge

+20 XP

Store 87 in an int variable marks and 87.5 in a double variable percent, then print: Marks: 87 Percent: 87.50

Output Loading C (first time takes a few seconds)
Press Run to see the result here.