C/C++ Arena

Step 1 of 6

Your first variable

So far the program only printed fixed text. Real programs work with data that changes: scores, prices, names. To keep a piece of data around, you store it in a variable.

A variable is a named box in the computer's memory. In C, every box has a type that says what kind of value it can hold, and the type never changes. You create (declare) a variable by writing the type, then the name:

int kills = 25;

Printing a variable

printf can't print a number directly inside the quotes, because the text in quotes is fixed. Instead you put a format specifier where the value should appear, and give the value after the string. For an int the specifier is %d (for decimal):

#include <stdio.h>

int main(void) {
    int kills = 25;
    int rounds = 16;
    printf("Kills: %d\n", kills);
    printf("Rounds played: %d\n", rounds);
    return 0;
}
Kills: 25
Rounds played: 16

Naming rules

Names can use letters, digits and underscores, but can't start with a digit, and can't be a C keyword like int or return. Names are case sensitive: score and Score are different variables. Pick names that say what the value means: total_price beats x.

Common mistakes

Your turn: declare an int named score with the value 42.

Next: Printing values with %d