Back to C Programming
2026-07-127 min read

Syntax of Scanf()

Learn Syntax of Scanf() step by step with clear examples and exercises.

Why This Matters

In C programming, scanf() is an essential function for creating interactive programs that can take user inputs dynamically. A solid understanding of its syntax and usage is crucial for acing coding interviews, solving real-world problems, and debugging common issues in your C programs.

Prerequisites

Before diving into scanf(), you should have a good grasp of:

  1. Basic C syntax: variables, data types, operators, and control structures like loops and conditionals.
  2. Input/Output (I/O) functions: printf() for outputting text to the console.
  3. Arrays: collections of elements of the same data type.
  4. Pointers: variables that store the memory address of other variables.
  5. Understanding the difference between value and reference, as well as call-by-value and call-by-reference paradigms in function arguments.
  6. Basic understanding of data types and their sizes (e.g., char, int, float, double).
  7. Familiarity with conditional statements and loops (if, else, for, while).

Core Concept

Syntax

The basic syntax of scanf() is as follows:

#include <stdio.h>

int main(void) {
// variable declaration
int num;

// reading input using scanf()
printf("Enter a number: ");
scanf("%d", &num);

// printing the entered number
printf("You entered: %d\n", num);

return 0;
}

In this example, we include the stdio.h header to access the input/output functions. We declare an integer variable named num, then use scanf() to read a number from the user and store it in the num variable. The format specifier %d tells scanf() that we want to read an integer. The ampersand (&) before the variable name is necessary because we are passing the memory address of the variable to scanf().

Format Specifiers

C provides various format specifiers for different data types:

  • %d or %i: for integers
  • %f: for floating-point numbers (float or double)
  • %c: for characters
  • %s: for strings (arrays of characters)
  • %o: for octal numbers
  • %x: for hexadecimal numbers

Reading Arrays and Multiple Variables

To read an array, you can pass the address of the first element. For example:

int arr[5];
scanf("%d %d %d %d %d", arr);

This will fill arr[0], arr[1], arr[2], arr[3], and arr[4] with the user's inputs, assuming they enter 5 integers separated by spaces.

Scanning Strings

To read a string using scanf(), you can use the %s format specifier:

char str[20];
scanf("%19s", str); // limits input to 19 characters

However, be careful when using this format specifier as it has security vulnerabilities. It does not check the size of the input array and may lead to buffer overflow if the user enters more characters than the allocated space. To avoid this issue, always limit the number of characters read by adding a maximum length in square brackets after the variable name:

char str[20];
scanf("%19s", str); // limits input to 19 characters

Pointer Concepts

To better understand why we need to use & before variables when using scanf(), let's dive deeper into pointers.

In C, a pointer is a variable that stores the memory address of another variable. When you declare a variable without using the & operator, its value is copied by value (not by reference) to the function argument list during function calls. However, when using scanf(), we need to pass the memory addresses of our variables so that scanf() can modify them directly.

When you use the & operator before a variable, it returns the memory address of that variable. This allows us to pass the memory addresses to functions like scanf() or printf(), enabling them to manipulate the original variable's value.

Worked Example

Let's create a simple program that reads two integers, calculates their sum, and outputs the result.

#include <stdio.h>

int main(void) {
int num1, num2, sum;

printf("Enter first number: ");
scanf("%d", &num1);

printf("Enter second number: ");
scanf("%d", &num2);

sum = num1 + num2;

printf("The sum is: %d\n", sum);

return 0;
}

Common Mistakes

  1. Not using the ampersand (&): Remember to use & before variables when using them with scanf().
  2. Forgetting space in format specifier: Always include a space between the percent sign (%) and the format specifier (e.g., %d, %s).
  3. Not checking for input errors: Use feof(stdin) or ferror(stdin) to check if there's an error reading from the standard input stream (keyboard).
  4. Buffer overflow when reading strings: Always limit the number of characters read by adding a maximum length in square brackets after the variable name.
  5. Not flushing the buffer: Use fflush(stdin) to clear the input buffer if you encounter unexpected behavior or want to ensure that all previously entered data is discarded before reading new inputs.
  6. Misunderstanding pointers and call-by-value vs call-by-reference: Understand why we need to use & with scanf() and how this relates to call-by-reference.
  7. Incorrect format specifiers: Ensure that the format specifier matches the data type of the variable being read. For example, using %d for a floating-point number will result in incorrect input parsing.
  8. Not handling negative numbers: When reading integers, ensure your program can handle both positive and negative values.
  9. Ignoring whitespace characters: Be aware that whitespace characters (spaces, tabs, newlines) are also considered as separators when using scanf(). This might lead to unexpected results if not handled properly.
  10. Not understanding the difference between scanf() and gets(): Understand the differences between these two functions, including their security implications and usage scenarios.

Practice Questions

  1. Write a program that reads three integers and finds their average.
  2. Modify the previous example to handle negative numbers and print the maximum and minimum number entered.
  3. Create a program that reads a string using scanf(), reverses it, and prints the reversed string.
  4. Write a program that converts temperatures from Fahrenheit to Celsius using scanf().
  5. Explain why we need to use the ampersand (&) before variables when using scanf() and how this relates to call-by-reference.
  6. Write a program that reads an array of integers using scanf() and finds the sum of all even numbers in the array.
  7. Create a program that reads a string using scanf(), counts the occurrence of each vowel (a, e, i, o, u) in it.
  8. Write a program that reads two floating-point numbers using scanf() and calculates their average while handling potential division by zero errors.
  9. Modify the worked example to read floating-point numbers instead of integers.
  10. Create a program that asks the user for a number n, then reads n integers and finds their sum.

FAQ

Why do we need to use the ampersand (&) before variables when using scanf()?

When you use the & operator before a variable, it returns the memory address of that variable. This allows us to pass the memory addresses to functions like scanf() or printf(), enabling them to manipulate the original variable's value directly. Without the ampersand, we would be passing the variable's value by value, which is not what we want when using input/output functions.

What happens if I forget the space in format specifiers like "%d" or "%s"?

If you forget the space between the percent sign (%) and the format specifier (e.g., %d, %s), it will lead to unexpected results, as whitespace characters are also considered separators when using scanf(). For example, if you use "%dn" instead of "%d ", the program may read an extra character as input or skip expected inputs.

Why is it important to limit the number of characters read by adding a maximum length in square brackets after the variable name when reading strings using scanf()?

When reading strings using scanf() with the %s format specifier, it does not check the size of the input array. If the user enters more characters than the allocated space, it may lead to buffer overflow, causing undefined behavior and potential security vulnerabilities. To avoid this issue, always limit the number of characters read by adding a maximum length in square brackets after the variable name.

What are some common mistakes when using scanf()?

Some common mistakes when using scanf() include:

  1. Not using the ampersand (&) before variables.
  2. Forgetting spaces in format specifiers.
  3. Not checking for input errors (e.g., using feof(stdin) or ferror(stdin)).
  4. Buffer overflow when reading strings.
  5. Not flushing the buffer with fflush(stdin).
  6. Misunderstanding pointers and call-by-value vs call-by-reference.
  7. Incorrect format specifiers (e.g., using %d for a floating-point number).
  8. Not handling negative numbers properly.
  9. Ignoring whitespace characters.
  10. Not understanding the difference between scanf() and gets().