Skip to content

int, double and char

Read · 1 of 5

Each type has its own format code

int holds whole numbers and prints with %d. double holds decimals and prints with %f; %.2f shows exactly 2 decimal places. char holds one character in single quotes, like 'A', and prints with %c.

Using the wrong code (say %d for a double) doesn't stop the program, it just prints garbage. Matching codes to types is your job.

Read this lesson as text

Whole numbers, decimals and single characters, and the format code for each.

Each type has its own format code

int holds whole numbers and prints with %d. double holds decimals and prints with %f; %.2f shows exactly 2 decimal places. char holds one character in single quotes, like 'A', and prints with %c.

Using the wrong code (say %d for a double) doesn't stop the program, it just prints garbage. Matching codes to types is your job.

Three types, three codes

#include <stdio.h>

int main() {
    int qty = 3;
    double price = 49.5;
    char grade = 'A';
    printf("%d x %.2f = %.2f\n", qty, price, qty * price);
    printf("Grade %c\n", grade);
    return 0;
}
  1. Line 4: A whole number.
  2. Line 5: A decimal number.
  3. Line 6: One character, written in single quotes.
  4. Line 7: Three placeholders, filled in order. %.2f rounds to 2 decimal places.
  5. Line 8: %c prints the character.

How many decimals?

#include <stdio.h>

int main() {
    double r = 2.0 / 3;
    printf("%.3f\n", r);
    return 0;
}

What does this print?

  • 0.667
  • 0.666
  • 0.67
Show the answer

0.667 %.3f shows 3 decimal places, rounding 0.6666… up to 0.667.

Characters are numbers too

#include <stdio.h>

int main() {
    char c = 'A';
    printf("%c %d\n", c + 2, c);
    return 0;
}

What does this print?

  • C 65
  • A 65
  • A+2 A
Show the answer

C 65 A char is stored as a number (its ASCII code): 'A' is 65, so 'A' + 2 is 67, which is 'C'.

Exercise: A canteen bill

Use variables: 2 samosas at 15.50 each and 1 tea at 12.00.

Print the total with two decimals: Total: Rs 43.00

Then print the first letter of your bill code, the char 'B': Code: B