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:
%dfor integers%ffor floating-point numbers
%cfor characters%sfor 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
EasyWrite a C program that does the following:
- Declare an integer variable
yearand initialize it with the value 2023. - Declare a float variable
piand initialize it with the value 3.14159. - Use
printf()to print these values in the following format:
The current year is 2023
The value of pi is 3.141590Make 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:
%dfor integers%ffor floating-point numbers%cfor characters%sfor 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;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge