🎓 A1Learner
🔍
0 of 50 lessons completed

C Variables

Comments were notes the compiler ignores. A variable is a named place that holds one value, and the program can swap it later.

Create and print a variable

age holds 25, and the print shows 25. The %d in the string is where the value goes.

#include <stdio.h>

int main() {
  int age = 25;
  printf("%d\n", age);
  return 0;
}

Change the value

score starts at 10, then takes the value 20. The print shows 20, so the new value replaced the old one.

#include <stdio.h>

int main() {
  int score = 10;
  score = 20;
  printf("%d\n", score);
  return 0;
}

Add two variables

a holds 3 and b holds 4, and total holds their sum. The print shows 7, so the addition worked.

#include <stdio.h>

int main() {
  int a = 3;
  int b = 4;
  int total = a + b;
  printf("%d\n", total);
  return 0;
}

Example

#include <stdio.h>

int main() {
  int apples = 5;
  int eaten = 2;
  int left = apples - eaten;
  printf("%d\n", left);
  return 0;
}

Key points

  • A variable has a type, a name, and a value.
  • int is the type for whole numbers.
  • int age = 25; creates a variable named age that holds 25.
  • The = sign gives the variable its first value.
  • A variable name starts with a letter.
  • printf with %d prints the value of an int variable.
  • Assigning a new value replaces the old value.

apples holds 5 and eaten holds 2, so 3 are left. The print shows 3, which proves the subtraction ran.

Note

Declare a variable before you use it.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which line creates a variable named score that holds 10?