Lesson 2 of 5

Variables, Data Types, and Operators

Declaring Variables in C

C is a statically typed language. Before you use a variable you must declare it with a specific type. The type tells the compiler how much memory to reserve and what kind of value the box can hold.

int age = 19;
float height = 1.63f;
char grade = 'A';
double price = 4999.99;

The Core Data Types

  • int — whole numbers, such as -7 or 250.
  • float — single-precision decimal numbers.
  • double — double-precision decimals, more accurate than float.
  • char — a single character, written in single quotes like 'A'.

Printing Values with Format Specifiers

printf uses format specifiers as placeholders. Each one is replaced by a value listed after the text.

int age = 19;
float height = 1.63f;
printf("Age: %d, Height: %.2f\n", age, height);
  • %d — an integer.
  • %f — a floating-point number; %.2f shows two decimals.
  • %c — a single character.
  • %s — a string of text.

Reading Input with scanf

The scanf function reads values typed by the user. Note the & symbol before the variable name — it gives scanf the memory address to store into.

int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("You typed %d\n", number);

Arithmetic Operators

int a = 17, b = 5;
printf("%d\n", a + b);   // 22
printf("%d\n", a / b);   // 3  integer division drops the fraction
printf("%d\n", a %% b);  // 2  remainder

An important detail: dividing two integers in C gives an integer result. 17 / 5 is 3, not 3.4. To get a decimal result, at least one value must be a float or double.

Always initialise your variables. An uninitialised variable in C holds an unpredictable “garbage” value left over in memory.
Next
How did you find this lesson?

Discussion

0
To join the discussion, comment and react, log in or create an account.

No comments yet — be the first to leave one!