C Programming Input/Output Functions
Essential Functions

C Input/Output Functions - Complete Guide

Master C input/output functions including printf(), scanf(), format specifiers, return values, and practical programming examples for effective C programming.

printf() & scanf()

Complete reference

Format Specifiers

Complete guide

Practical Examples

Real-world usage

Introduction to C Input/Output

Input/Output (I/O) operations are fundamental to any programming language. In C, I/O is performed using functions from the standard library stdio.h (Standard Input/Output). These functions allow programs to communicate with users by reading input and displaying output.

Key Concepts
  • Include #include <stdio.h> for I/O functions
  • printf() - Output function for displaying data
  • scanf() - Input function for reading data
  • Format specifiers define data type for I/O operations
  • Return values indicate success/failure of operations
Common I/O Functions
  • printf(): Formatted output to console
  • scanf(): Formatted input from console
  • getchar(): Read single character
  • putchar(): Write single character
  • gets() / fgets(): Read string input
  • puts(): Write string output

Important Note About stdio.h

The stdio.h header file must be included at the beginning of any C program that uses input/output functions. This file contains declarations for all standard I/O functions and is part of the C Standard Library.

C Program Execution

Before you use printf() and scanf(), it helps to know how a C program moves from source code to running output. A .c file is edited, processed by the preprocessor, compiled into object code, linked into an executable, loaded into memory, and then executed—starting at main().

Flowchart of C program execution from source code through preprocessing, compilation, linking, loading, and running with input and output
C program execution: Source file → preprocessor → compiler → linker → executable → runtime (load & run) → printf/scanf interact with standard input and output.
Build Steps
  • Preprocess: Handles #include and macros
  • Compile: Translates C to machine code (object file)
  • Link: Combines object files and libraries into .exe
At Runtime
  • OS loads the program and calls main()
  • printf() writes formatted data to stdout
  • scanf() reads formatted data from stdin
  • Program ends when main() returns

The printf() Function - Complete Guide

The printf() function is used to display formatted output to the standard output (usually the console/screen). It's the most commonly used output function in C.

Syntax:
int printf(const char *format, ...);

Parameters:

Parameter Description Example
format Format string containing text and format specifiers
"Value: %d"
... Variable number of arguments matching format specifiers
10, "Hello", 3.14, etc.

Return Value:

  • Returns the number of characters printed (excluding the null character)
  • Returns a negative value if an error occurs
  • printf("Hello"); returns 5
  • printf("Number: %d", 42); returns 9 ("Number: 42" has 9 characters)

Common Format Specifiers for printf():

Specifier Data Type Description Example
%d int Signed decimal integer
printf("%d", 42);
%i int Signed decimal integer (same as %d)
printf("%i", 42);
%u unsigned int Unsigned decimal integer
printf("%u", 100U);
%f float/double Decimal floating point (default 6 decimal places)
printf("%f", 3.14159);
%c char Single character
printf("%c", 'A');
%s char* (string) String of characters
printf("%s", "Hello");
%p void* Pointer address
printf("%p", &variable);
%x unsigned int Hexadecimal integer (lowercase)
printf("%x", 255); // ff
%X unsigned int Hexadecimal integer (uppercase)
printf("%X", 255); // FF
%o unsigned int Octal integer
printf("%o", 64); // 100
%e float/double Scientific notation (lowercase)
printf("%e", 1234.567);
%E float/double Scientific notation (uppercase)
printf("%E", 1234.567);
%g float/double Uses %e or %f, whichever is shorter
printf("%g", 1234.567);
%G float/double Uses %E or %f, whichever is shorter
printf("%G", 1234.567);
%% None Prints a literal % character
printf("Discount: 10%%");

printf() Examples:

Basic printf() Examples

#include <stdio.h>

int main() {
    int age = 25;
    float salary = 45000.50;
    char grade = 'A';
    char name[] = "John Doe";
    
    // Basic examples
    printf("Hello, World!\n");
    
    // Integer output
    printf("Age: %d\n", age);
    printf("Age in hex: %x\n", age);
    
    // Floating point output
    printf("Salary: %f\n", salary);
    printf("Salary with 2 decimals: %.2f\n", salary);
    
    // Character output
    printf("Grade: %c\n", grade);
    
    // String output
    printf("Name: %s\n", name);
    
    // Multiple values
    printf("Employee: %s, Age: %d, Salary: $%.2f, Grade: %c\n", 
           name, age, salary, grade);
    
    // Return value demonstration
    int chars_printed = printf("This is a test\n");
    printf("Characters printed: %d\n", chars_printed - 1); // -1 for \n
    
    return 0;
}
                
Output:
Hello, World!
Age: 25
Age in hex: 19
Salary: 45000.500000
Salary with 2 decimals: 45000.50
Grade: A
Name: John Doe
Employee: John Doe, Age: 25, Salary: $45000.50, Grade: A
This is a test
Characters printed: 14

The scanf() Function - Complete Guide

The scanf() function is used to read formatted input from the standard input (usually the keyboard). It's the most commonly used input function in C.

Syntax:
int scanf(const char *format, ...);

Parameters:

Parameter Description Important Notes
format Format string containing format specifiers Must match the type of variables being read
... Pointer to variables where input will be stored Variables must be passed using address-of operator (&)

Return Value:

  • Returns the number of input items successfully matched and assigned
  • Returns EOF if end-of-file is reached or an error occurs before any conversion
  • Returns 0 if no input items are matched
  • scanf("%d", &num); returns 1 if successful, 0 if input is not a number
  • scanf("%d %f", &a, &b); returns 2 if both values are read successfully

Common Format Specifiers for scanf():

Specifier Data Type Description Example
%d int* Signed decimal integer
scanf("%d", &number);
%i int* Integer (decimal, octal with 0, hex with 0x)
scanf("%i", &number);
%u unsigned int* Unsigned decimal integer
scanf("%u", &value);
%f float* Floating point number
scanf("%f", &floatValue);
%lf double* Double precision floating point
scanf("%lf", &doubleValue);
%c char* Single character (reads whitespace too)
scanf("%c", &ch);
%s char* String (stops at whitespace)
scanf("%s", name);
%[ ] char* Scanset - reads characters matching set
scanf("%[A-Z]", uppercase);
%x unsigned int* Hexadecimal integer
scanf("%x", &hexValue);
%o unsigned int* Octal integer
scanf("%o", &octValue);

scanf() Examples:

Basic scanf() Examples

#include <stdio.h>

int main() {
    int age;
    float height;
    char initial;
    char name[50];
    double salary;
    
    // Reading integer input
    printf("Enter your age: ");
    int result1 = scanf("%d", &age);
    printf("Age: %d, scanf returned: %d\n", age, result1);
    
    // Reading float input
    printf("Enter your height in meters: ");
    int result2 = scanf("%f", &height);
    printf("Height: %.2f meters, scanf returned: %d\n", height, result2);
    
    // Reading character input (note: reads whitespace)
    printf("Enter your initial: ");
    int result3 = scanf(" %c", &initial); // Space before %c ignores whitespace
    printf("Initial: %c, scanf returned: %d\n", initial, result3);
    
    // Reading string input (stops at whitespace)
    printf("Enter your first name: ");
    int result4 = scanf("%s", name);
    printf("Name: %s, scanf returned: %d\n", name, result4);
    
    // Reading multiple values at once
    printf("Enter age and height (separated by space): ");
    int age2;
    float height2;
    int result5 = scanf("%d %f", &age2, &height2);
    printf("Age: %d, Height: %.2f, scanf returned: %d\n", age2, height2, result5);
    
    // Reading double precision
    printf("Enter your salary: ");
    int result6 = scanf("%lf", &salary);
    printf("Salary: %.2lf, scanf returned: %d\n", salary, result6);
    
    // Checking return value for error handling
    int number;
    printf("Enter a number: ");
    if (scanf("%d", &number) == 1) {
        printf("Successfully read: %d\n", number);
    } else {
        printf("Invalid input!\n");
        // Clear input buffer
        while (getchar() != '\n');
    }
    
    return 0;
}
                
Sample Output:
Enter your age: 25
Age: 25, scanf returned: 1
Enter your height in meters: 1.75
Height: 1.75 meters, scanf returned: 1
Enter your initial: J
Initial: J, scanf returned: 1
Enter your first name: John
Name: John, scanf returned: 1
Enter age and height (separated by space): 30 1.80
Age: 30, Height: 1.80, scanf returned: 2
Enter your salary: 50000.75
Salary: 50000.75, scanf returned: 1
Enter a number: abc
Invalid input!

Practical Examples - printf() and scanf() Together

Short programs that show printf() and scanf() working together. Each example also uses return values for input checks or output length.

Example 1: Add Two Numbers

#include <stdio.h>

int main() {
    int a, b, n, chars;

    printf("Enter two integers: ");
    n = scanf("%d %d", &a, &b);
    if (n != 2) {
        printf("scanf failed (returned %d)\n", n);
        return 1;
    }

    chars = printf("Sum = %d\n", a + b);
    printf("printf returned %d characters\n", chars);
    return 0;
}
                
Example 2: Name and Age

#include <stdio.h>

int main() {
    char name[20];
    int age, n;

    printf("Name: ");
    scanf("%19s", name);
    printf("Age: ");
    n = scanf("%d", &age);
    if (n == 1)
        printf("Hello %s, age %d\n", name, age);
    else
        printf("Bad age input (scanf returned %d)\n", n);
    return 0;
}
                
Example 3: Celsius to Fahrenheit

#include <stdio.h>

int main() {
    float c, f;
    int n;

    printf("Celsius: ");
    if (scanf("%f", &c) != 1) {
        printf("Invalid input\n");
        return 1;
    }
    f = (c * 9.0f / 5.0f) + 32.0f;
    n = printf("%.1f C = %.1f F\n", c, f);
    printf("(printf returned %d)\n", n);
    return 0;
}
                

Tricky Points: printf and scanf Return Values

Return values are easy to ignore, but they matter in interviews and for safe input handling.

Tricky Point 1: printf() returns the number of characters written, or a negative value on error.
int n = printf("Hi"); // n is 2 int m = printf("Num: %d", 42); // m is 7 ("Num: 42")

Return type is int, not void.

Tricky Point 2: scanf() returns how many items were successfully read and stored—not whether Enter was pressed.
scanf("%d %d", &a, &b); // returns 2 if both ints read scanf("%d", &x); // returns 1 on success scanf("%d", &x); // returns 0 if input is "abc"
Tricky Point 3: Compare scanf return to the number of conversions you expect.
if (scanf("%d %f", &i, &f) != 2) { printf("Expected int and float\n"); }

Partial success: input 10 x for %d %d returns 1, not 0.

Tricky Point 4: scanf returns EOF when input ends before any conversion (usually -1).
while (scanf("%d", &n) == 1) { /* process n */ }

EOF is not the same as return 0. Zero means no match; EOF means no more input.

Tricky Point 5: A failed scanf leaves bad characters in the buffer and breaks the next read.
if (scanf("%d", &n) != 1) { while (getchar() != '\n'); // clear bad line }

Always check the return value and flush invalid input before calling scanf again.

Tricky Point 6: printf return counts characters; a newline \n counts as one character.
printf("OK\n"); // returns 3, not 2

Use the return value for logging or buffer sizing, not as a success/fail flag for normal output.

Common Mistakes and Best Practices

Common Mistake 1: Forgetting & (address-of operator) in scanf()
int num; scanf("%d", num); // WRONG - missing &
int num; scanf("%d", &num); // CORRECT
Common Mistake 2: Wrong format specifier
double salary; scanf("%f", &salary); // WRONG - use %lf for double
double salary; scanf("%lf", &salary); // CORRECT
Common Mistake 3: Buffer overflow with strings
char name[10]; scanf("%s", name); // DANGEROUS - no limit on input size
char name[10]; scanf("%9s", name); // SAFER - limits to 9 chars + null terminator
Common Mistake 4: Newline character left in buffer
int age; char grade; scanf("%d", &age); scanf("%c", &grade); // Reads leftover newline!
int age; char grade; scanf("%d", &age); scanf(" %c", &grade); // CORRECT - space before %c
Best Practices for C I/O:
  1. Always check the return value of scanf() to verify successful input
  2. Use field width specifiers with %s to prevent buffer overflows
  3. Include a space before %c in scanf() to skip whitespace
  4. Use %.2f or similar to control decimal places in output
  5. Clear the input buffer after failed scanf() calls: while(getchar() != '\n');
  6. Always prompt the user before scanf() so they know what to enter
  7. Use printf() return value for debugging output issues

Key Takeaways

  • Always include #include <stdio.h> for I/O functions
  • printf() displays formatted output and returns the number of characters printed
  • scanf() reads formatted input and returns the number of successful conversions
  • Use & (address-of operator) with variables in scanf() (except arrays)
  • Format specifiers must match the data type: %d for int, %f for float, %lf for double
  • Use " %c" (space before %c) in scanf() to skip whitespace when reading characters
  • Check scanf() return value to validate user input
  • Limit string input with field width: %9s for 9 characters maximum
  • Control floating point precision: %.2f for 2 decimal places
  • Clear input buffer after errors: while(getchar() != '\n');
Next Topics: We'll cover all types of operators in detail with practical programming examples.