Menu
Coddy logo textTech

printf Basics

Part of the Fundamentals section of Coddy's C journey — lesson 11 of 63.

In C, the printf() function is used to print formatted output to the console. It's part of the standard input/output library <stdio.h>.

The basic syntax of printf() is:

printf("format string", argument1, argument2, ...);

The format string can contain:

  • Plain text, which is printed as-is
  • Format specifiers, which start with % and are replaced by the values of the arguments

Here are some common format specifiers:

  • %d for integers
  • %f for floating-point numbers
  • %c for characters
  • %s for strings

Example:

int age = 25;
printf("I am %d years old.\n", age);

This will output: I am 25 years old.

The \n at the end of the string is a newline character, which moves the cursor to the next line after printing.

challenge icon

Challenge

Easy

Write a C program that does the following:

  1. Declare an integer variable year and initialize it with the value 2023.
  2. Declare a float variable pi and initialize it with the value 3.14159.
  3. Use printf() to print these values in the following format:
The current year is 2023
The value of pi is 3.141590

Make sure to use appropriate format specifiers for each variable type. Note that %f prints float values with 6 decimal places by default, so 3.14159 will be displayed as 3.141590.

Cheat sheet

The printf() function prints formatted output to the console and requires <stdio.h>:

printf("format string", argument1, argument2, ...);

Common format specifiers:

  • %d for integers
  • %f for floating-point numbers
  • %c for characters
  • %s for strings

Example:

int age = 25;
printf("I am %d years old.\n", age);

Use \n for newlines.

Try it yourself

#include <stdio.h>

int main() {
    // Declare and initialize your variables here
    
    // Your printf statements here
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals