---
title: "Syntax and example of scanf()"
subject: "Computer Programming"
chapter: 4
key: "semester_1/computer_programming:syntax-scanf"
source: https://www.bctengineer.com/q/semester_1/computer_programming/syntax-scanf
site: BCT Engineering
---

# Syntax and example of scanf()

Computer Programming · Chapter 4: Input and Output

- Asked in: 2071 Shrawan, 1 marks; 2071 Chaitra, 1 marks; 2072 Chaitra, 1 marks; 2067 Asar, 2 marks (asked 4 times)
- Video: [Basic Input Function – scanf](https://www.youtube.com/watch?v=ZSZwDARaQYI) — Neso Academy
- Answer checked by Claude Opus 5.5 (high effort) on 2026-10-14
- Page: https://www.bctengineer.com/q/semester_1/computer_programming/syntax-scanf
- Whole chapter: https://www.bctengineer.com/md/semester_1/computer_programming/chapter-4

## Question

Write syntax and example of scanf().

## Short answer

scanf() reads formatted input from stdin. Syntax: scanf("format string", &var1, &var2, ...); with format specifiers like %d. Example: scanf("%d %f %c", &roll, &marks, &grade); reads an integer, float, and character, then printf displays them.

## Answer

`scanf()` reads formatted input from the keyboard (standard input) and stores it in variables. It is declared in `<stdio.h>`.

**Syntax:** `scanf("format specifiers", &var1, &var2, ...);`

- The format string says the type of each input (`%d` int, `%f` float, `%c` char, `%s` string).
- The address operator `&` is required for ordinary variables (not for strings).
- It returns the number of values successfully read.

**Example:**
```c
#include <stdio.h>
int main(void)
{
    int roll;
    float marks;
    char grade;
    scanf("%d %f %c", &roll, &marks, &grade);
    printf("Roll=%d Marks=%.1f Grade=%c\n", roll, marks, grade);
    return 0;
}
```
For input `7 85.5 A`, output:
```text
Roll=7 Marks=85.5 Grade=A
```

## Check yourself

The answer's key points as multiple-choice questions, with the correct option and why.

1. What does scanf() do?
   A. Prints output
   B. Reads formatted input and stores it in variables
   C. Reads one character without echo
   D. Opens a file
   Answer: B. scanf reads formatted keyboard input. (Key point: Purpose)

2. Why is & needed in scanf("%d", &roll)?
   A. scanf needs the address of the variable
   B. To make it a pointer type
   C. To print the address
   D. It is optional
   Answer: A. scanf stores into memory, so it needs the variable's address (not for strings). (Key point: Ampersand)

3. What does scanf return?
   A. The first value read
   B. The number of values successfully read
   C. Always 0
   D. The address
   Answer: B. It returns the count of values read successfully. (Key point: Return value)
