Learn C# · lesson 2 of 61 · about 6 minutes
Variables
Track health points in int variables, change them as the battle goes on, and print them.
What you'll learn
- Make a variable with a type
- Use int for whole numbers and double for decimals
- Change a value with =
Health points
Every battle tracks numbers that change: health, damage, turns. Keep each one in a variable: a value with a name. In C# you say what type it holds when you make it:
intholds whole numbers, like30or-5doubleholds numbers with a decimal point, like1.5
When you print, + joins text and a value: "Slime HP: " + slimeHp.
Two fighters
int heroHp = 30;
int slimeHp = 12;
Console.WriteLine("Hero HP: " + heroHp);
Console.WriteLine("Slime HP: " + slimeHp);Output
Hero HP: 30
Slime HP: 12Values change
Once a variable exists, = gives it a new value, and the old one is gone. Here = stores a value: it doesn't ask whether two things are equal.
slimeHp = slimeHp - 5; works out the right side first, using the old value, then stores the answer.
Step through it to watch the Slime's health drop
int slimeHp = 12;
slimeHp = slimeHp - 5;
slimeHp = slimeHp - 4;
Console.WriteLine("Slime HP: " + slimeHp);Output
Slime HP: 3Tip
Write the type only once, when you make the variable. After that, use just the name: writing int slimeHp a second time would make another variable with the same name, and the compiler stops you.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.