0
0
Cprogramming~5 mins

Using scanf for input

Choose your learning style9 modes available
Introduction

We use scanf to get information from the user while the program is running. It helps the program read what the user types.

When you want to ask the user for their age and use it in the program.
When you need to get a number from the user to do math calculations.
When you want to read a word or sentence typed by the user.
When you want to make a simple quiz that asks questions and reads answers.
When you want to get multiple pieces of information at once, like name and score.
Syntax
C
scanf("%format_specifier", &variable);

The format_specifier tells scanf what type of data to expect, like %d for integers or %f for decimals.

The & symbol before the variable means 'address of' and is needed so scanf can store the input in the right place.

Examples
This reads an integer number from the user and saves it in the variable age.
C
int age;
scanf("%d", &age);
This reads a decimal number (float) from the user and saves it in price.
C
float price;
scanf("%f", &price);
This reads a word (string) from the user and saves it in the array name. No & needed for arrays.
C
char name[20];
scanf("%s", name);
Sample Program

This program asks the user to enter their age, reads it using scanf, and then prints it back.

C
#include <stdio.h>

int main() {
    int age;
    printf("Enter your age: ");
    scanf("%d", &age);
    printf("You are %d years old.\n", age);
    return 0;
}
OutputSuccess
Important Notes

Always use the correct format specifier for the type of data you want to read.

For strings (arrays), do not use & before the variable name.

scanf stops reading a string at the first space, so it reads only one word.

Summary

scanf reads user input during program execution.

Use format specifiers like %d, %f, and %s to tell scanf what to expect.

Remember to use & before variables except for arrays when using scanf.