C Programming: Memory, Pointers and the Stack ยท C Basics

printf: Printing Values

Print numbers, decimals and characters with printf and format codes like %d, %.2f and %c.

printf_basics.c

#include <stdio.h>

int main(void) {
    int age = 21;
    double price = 4.5;
    char grade = 'A';
    printf("Age: %d\n", age);
    printf("Price: %.2f\n", price);
    printf("Grade: %c, padded: [%5d]\n", grade, age);
    return 0;
}

Step by step

  1. age is an int: a whole number, stored on the stack.
  2. price is created on the stack with the value 4.5.
  3. A char holds one character, written in single quotes.
  4. %d is replaced by the int age. \n moves to a new line.
  5. %.2f prints a double with exactly two decimals: 4.50.
  6. %c prints a char; %5d pads the number to 5 characters wide.
  7. The method returns 0.
  8. Three lines printed. Each % code took the next value in order and formatted it by its type.