Back to course

Basic Input and Output: printf and scanf

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 9: Basic Input and Output: printf and scanf

These functions are part of the stdio.h library and are essential for user interaction.

Output: printf()

printf() is used to display output on the standard output stream (usually the console).

Format Specifiers

printf uses format specifiers to understand how to interpret and display variables.

SpecifierUsed forExample
%d or %iDecimal integers (int)printf("%d", age);
%fFloating point (float/double)printf("%f", price);
%.2fFloating point (2 decimal places)printf("%.2f", price);
%cSingle character (char)printf("%c", initial);
%sString (sequence of characters)printf("%s", name);

c #include <stdio.h>

int main() { int item_count = 5; float cost = 49.95; printf("Total items: %d. Cost: $%.2f.\n", item_count, cost); return 0; }

Input: scanf()

scanf() is used to read data from the standard input stream (keyboard).

Crucial Rule: When reading basic variables with scanf, you must pass the address of the variable using the address-of operator (&).

c #include <stdio.h>

int main() { int user_age; printf("Enter your age: "); // Notice the & before user_age scanf("%d", &user_age); printf("You are %d years old.\n", user_age); return 0; }

Failure to use & in scanf for non-array variables is a common mistake and leads to undefined behavior.