C

Input and Output in C: printf() and scanf()

In C programming, the stdio.h (Standard Input Output) library provides functions to interact with the user. The two most fundamental functions are printf() for output and scanf() for input.

1. The printf() Function

The printf() function is used to print formatted output to the standard output device (usually the screen).

  • Syntax: printf("format string", arguments);

  • Theory: The "format string" contains text to be printed and format specifiers that act as placeholders for the variables passed as arguments.

Common Format Specifiers:

SpecifierData Type
%d or %iInteger (int)
%fFloating-point (float)
%lfDouble-precision floating-point (double)
%cCharacter (char)
%sString (array of characters)

Escape Sequences:

These are used inside printf() to format the layout:

  • \n: Moves the cursor to a new line.

  • \t: Inserts a horizontal tab.

  • \\: Prints a backslash.

  • \": Prints double quotes.

2. The scanf() Function

The scanf() function is used to read formatted input from the standard input device (usually the keyboard).

  • Syntax: scanf("format string", &variable);

  • Theory: The scanf() function requires the address of the variable where the input should be stored. This is why we use the ampersand (&) symbol, known as the "address-of" operator.

Note: For strings (%s), the & is typically not required because the name of a character array already represents its starting address.

3. Practical Code Example

This program demonstrates how to take an integer and a float as input and display them back to the user.

#include <stdio.h>

int main() {
    int age;
    float salary;

    // Output using printf
    printf("Enter your age: ");
    
    // Input using scanf (Note the & operator)
    scanf("%d", &age);

    printf("Enter your expected salary: ");
    scanf("%f", &salary);

    // Displaying the results
    printf("\n--- User Profile ---\n");
    printf("Age: %d years old\n", age);
    printf("Salary: $%.2f per month\n", salary); // %.2f limits to 2 decimal places

    return 0;
}

4. Key Differences Summary

Featureprintf()scanf()
PurposeTo display output.To read input.
OperatorNo special operator needed for variables.Requires & (address-of) operator.
FunctionalityConverts internal values to text.Converts text input to internal values.
FormatCan include plain text and escape codes.Mostly contains format specifiers.
Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now