Understanding printf and scanf in C — A Beginner’s Guide

 


When you start programming in C, two of the most fundamental functions you’ll use for input/output are printf and scanf. These functions (declared in <stdio.h>) let you print output to the console and read input from the user (via standard input). Getting comfortable with them—and especially with format specifiers—is key to writing interactive C programs.

In this article, we’ll explore:

  1. The syntax and usage of printf
  2. The syntax and usage of scanf
  3. Common pitfalls and best practices
  4. Examples
  5. Assignments / practice problems

1. printf — printing formatted output

  1. Basic syntax

    #include <stdio.h>

     

    int printf(const char *format, …);

    • format is a string literal (or char pointer) that may include plain text and format specifiers (like %d, %f, etc.).
    • The … indicates a variable number of additional arguments (one for each format specifier) that supply the values to print.

    Common format specifiers

    Specifier

    Type printed

    Example usage

    %d or %i

    int

    prints an integer

    %u

    unsigned int

    prints an unsigned integer

    %f

    double

    prints a floating-point (decimal) number

    %lf

    double (same as %f for printf)

    %c

    char

    prints a single character

    %s

    char * (string)

    prints a null-terminated string

    %p

    pointer

    prints an address in implementation-defined format

    %x, %X

    unsigned in hex

    prints in lowercase/uppercase hexadecimal

    %%

    prints a literal % character

    Note: printf promotes float to double, so when passing floats, you typically pass as double.

Examples


#include <stdio.h>
int main(void) {
int a = 10;
double pi = 3.14159;
char ch = 'A';
char *msg = "Hello, ProgVeda!";
printf("Integer a = %d\n", a);
printf("Floating point pi = %f\n", pi);
printf("Character ch = %c\n", ch);
printf("Message: %s\n", msg);
printf("Hex of a = 0x%x\n", a);
printf("Show percent sign: 100%% sure!\n");
return 0;
}


Output:

Integer a = 10

Floating point pi = 3.141590

Character ch = A

Message: Hello, ProgVeda!

Hex of a = 0xa

Show percent sign: 100% sure!

Explanation

  • printf("Integer a = %d\n", a);: the %d is replaced by the value of a.
  • printf("Floating point pi = %f\n", pi);: %f prints a double with default precision (6 decimal places).
  • printf("Show percent sign: 100%% sure!\n");: %% in the format string is how you escape and print a literal %.

You can also control width and precision:

printf("Pi to 2 decimals: %.2f\n", pi);       // prints 3.14 

printf("Padded int: %5d\n", a);              // prints “   10” (width 5) 

printf("Left align: %-5d end\n", a);         // prints “10    end” 

printf("Zero padded: %05d\n", a);            // prints “00010” 


2. scanf — reading formatted input

Basic syntax

#include <stdio.h>

 

int scanf(const char *format, …);

  • format is a string with format specifiers (similar to printf), but each specifier must correspond to a pointer argument (where the input will be stored).
  • The return value is the number of input items successfully matched and assigned (or EOF on error).

Common specifiers (in scanf)

Many of the same specifiers as printf exist (%d, %f, %s, etc.), but with key differences:

  • %d expects a pointer to int (i.e. &myInt)
  • %f expects a pointer to float
  • %lf expects double *
  • %c expects a pointer to char
  • %s expects a char * (an array or buffer)
  • %[...] for scansets (e.g. %[a-z])
  • Whitespace (space, \n, \t) in the format string can skip whitespace in input

Examples


#include <stdio.h>
int main(void) {
int age;
double salary;
char name[50];
printf("Enter your age: ");
if (scanf("%d", &age) != 1) {
// input error
printf("Invalid input for age.\n");
return 1;
}
printf("Enter your salary: ");
scanf("%lf", &salary); // double
printf("Enter your name: ");
scanf("%49s", name); // read a word (max 49 chars + null)
printf("Hello, %s! Age = %d, Salary = %.2lf\n", name, age, salary);
return 0;
}


If you run and input:

30

4500.50

Alice

The output would be:

Hello, Alice! Age = 30, Salary = 4500.50

Important points & pitfalls

  1. Buffer overflow risk with %s
    Always limit the width, e.g. %49s so that you don’t overflow a buffer of size 50.
  2. Whitespace issues with %c and %[ ]
    Reading a character immediately after reading a number may capture a leftover newline. Use a space before %c like " %c" to skip whitespace.
  3. Return value of scanf
    Always check the return: it tells you how many items were matched. If it’s less than expected, input failed.
  4. Mixing scanf with fgets or other input methods
    Be careful with newline leftovers. Sometimes it’s easier to read a full line as a string (via fgets) and then parse using sscanf.
  5. Invalid input types
    If you expect an integer but user types non-digit, scanf fails to match and the variable remains unchanged (or undefined). That’s why checking return is important.

3. Combined Example

Here’s a more complete example illustrating input, validation, and output.



#include <stdio.h>
int main(void) {
int n;
printf("How many numbers do you want to input (1-10)? ");
if (scanf("%d", &n) != 1 || n < 1 || n > 10) {
printf("Invalid number count.\n");
return 1;
}
double arr[10];
for (int i = 0; i < n; i++) {
printf("Enter value %d: ", i + 1);
if (scanf("%lf", &arr[i]) != 1) {
printf("Invalid input. Aborting.\n");
return 1;
}
}
double sum = 0.0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
double avg = sum / n;
printf("You entered %d numbers. Sum = %.2lf, Average = %.2lf\n", n, sum, avg);
return 0;
}


Sample run:

How many numbers do you want to input (1-10)? 3

Enter value 1: 10.5

Enter value 2: 20.0

Enter value 3: 5.25

You entered 3 numbers. Sum = 35.75, Average = 11.92

4. Practice Assignments

Here are some exercises you can try. Use printf and scanf (and always check the scanf return value) to implement:

  1. Swap two numbers
    Read two integers from the user and swap their values, then print both before and after swapping.

Example:

Enter x: 5

Enter y: 10

Before swap: x = 5, y = 10

After swap:  x = 10, y = 5

  1. Fibonacci series
    Read an integer n (say up to 20) and print the first n terms of the Fibonacci sequence.
  2. Find maximum and minimum
    Read n (say up to 20), then read n integers into an array, then print the maximum and minimum values.
  3. Formatted table
    Read n (up to e.g. 10), then read n integers. Print a two-column table:
  4. Index   Value
  5. 1       5
  6. 2       8
  7. 3       2
  8. ...

Use width specifiers so columns align nicely.

  1. Robust input
    Modify any one of the above such that if a user enters invalid input (e.g. a non-numeric string when expecting an integer), your program gracefully handles it (prints an error and exits or asks again).

5. Tips & Summary

  • printf is for output; scanf is for input.
  • Always include <stdio.h>.
  • In printf, format specifiers correspond to values. In scanf, they correspond to pointers (addresses).
  • Always check the return value of scanf to detect input errors.
  • Be careful about buffer overflow with %s, and newline/whitespace issues with %c.
  • Use width and precision specifiers (%5d, %.2f, etc.) to control formatting.
  • For more flexible input, consider reading lines via fgets and parsing via sscanf.

Post a Comment

Previous Post Next Post