CodeMIRAI
0 XP

Variables and data types

2 min read 5 runnable examples Quiz included

In C, every variable has a type, declared before it's used. The type decides what the variable can hold and how much memory it takes.

The basic types

TypeHoldsExampleprintf
intwhole numbersint age = 21;%d
floatdecimal numbers (about 7 digits)float price = 9.99;%f
doubledecimal numbers (about 15 digits)double pi = 3.14159265;%f
chara single characterchar grade = 'A';%c
C
#include <stdio.h>

int main() {
    int age = 21;
    double height = 1.65;
    char grade = 'A';

    printf("Age: %d\n", age);
    printf("Height: %f\n", height);
    printf("Height: %.2f\n", height);
    printf("Grade: %c\n", grade);
    return 0;
}

The %d, %f and %c are format specifiers: placeholders that printf fills with the values that follow, in order. %.2f shows two decimal places.

Declaring and assigning

C
#include <stdio.h>

int main() {
    int score;          // declared, but not given a value yet
    score = 50;         // assigned
    score = score + 25; // changed
    int a = 1, b = 2, c = 3;
    printf("%d %d %d %d\n", score, a, b, c);
    return 0;
}

Characters are numbers

A char is stored as a small number (its ASCII code), so you can do arithmetic with it:

C
#include <stdio.h>

int main() {
    char letter = 'A';
    printf("%c has code %d\n", letter, letter);
    printf("Two letters later: %c\n", letter + 2);
    return 0;
}

Constants

const makes a variable that can't be changed after it's set:

C
#include <stdio.h>

int main() {
    const double PI = 3.14159;
    double radius = 2.0;
    printf("Area: %.2f\n", PI * radius * radius);
    return 0;
}

Integer division

Dividing two ints throws away the remainder. Make one side a decimal to get a decimal result:

C
#include <stdio.h>

int main() {
    int a = 7, b = 2;
    printf("%d\n", a / b);
    printf("%d\n", a % b);
    printf("%.1f\n", (double)a / b);
    return 0;
}

(double)a is a cast: it converts a to a double just for this calculation.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.