Variables, Data Types & Input

User Keyboard Input with scanf() & Address-Of (&)

Read keyboard input typed by the user into variables using scanf and the address operator &.

1. The Hook Imagine filling out a physical registration form at your college admission counter. The form has blank boxes labeled *Name*, *Roll Number*, and *Mobile*.

When you hand the form to the officer, they look at the label on each box and write your details into the corresponding ledger page.

In C programming, scanf() is the admission officer reading keyboard input into variable memory boxes!


2. Real World Story When you type on a keyboard, keypresses send electrical signals to your operating system. But your code needs to place those numbers into specific RAM locations.


3. Problem How does scanf() know WHERE in RAM to place the numbers typed on the keyboard?


4. Concept: The Address-Of & Operator

Syntax: scanf("%d", &age);

The ampersand symbol & in &age means "Address of age".

Every variable box lives at a numeric RAM address (e.g. 0x7ffe4a80). Passing &age gives scanf() the exact RAM street address so it can drop the input directly into that RAM cell!


5. Mental Model - `age` = The content inside the box. - `&age` = The GPS house address of the box written on an envelope.


6. Visualization

Keyboard Input "20"  --->  scanf("%d", &age)  --->  Finds RAM Address 0x7ffe4a80  --->  Stores 20 inside age

7. Code Example

#include <stdio.h>

int main() { int rollNo; printf("Enter Roll Number: "); rollNo = 101; // Simulated keyboard input printf("Roll Number = %d\n", rollNo); return 0; } ```


8. Common Mistakes - Forgetting `&` in `scanf`: Writing scanf("%d", age); passes an uninitialized number instead of a RAM address, causing a Segmentation Fault (Core Dumped) crash!


9. Viva Corner - Q: Why do we use & in scanf but NOT in printf? - A: scanf needs the RAM memory address to *store* data into the variable. printf only needs the value inside the variable to *display* it.


10. Summary Today you learned how to read user keyboard input using scanf() and the address-of operator &!