scanf Basics
Part of the Fundamentals section of Coddy's C journey — lesson 33 of 63.
In C, the scanf() function is used to read formatted input from the user. It's part of the standard input/output library <stdio.h>.
The basic syntax of scanf() is:
scanf("format string", &variable1, &variable2, ...);The format string contains format specifiers that match the types of variables you're reading. Common format specifiers include:
%dfor integers%ffor floats%lffor doubles
%cfor characters%sfor strings
Note the use of the ampersand (&) before variable names. This is because scanf() needs the memory address of the variable to store the input.
Example:
int age;
scanf("%d", &age);This will prompt the user to enter their age, and the entered value will be stored in the age variable.
Challenge
EasyWrite a C program that does the following:
- Declare an integer variable
num1and a float variablenum2. - Use
scanf()to read an integer value intonum1and a float value intonum2from the user. - Calculate the sum of
num1andnum2and store it in a variable calledsum. - Print the values of
num1,num2, andsumusingprintf(). Printnum2andsumwith exactly 2 decimal places using the%.2fformat specifier.
Use appropriate format specifiers for input and output. The output format should match this example:
num1 = 5<br>num2 = 3.14<br>sum = 8.14Try it yourself
#include <stdio.h>
int main() {
// Declare your variables here
// Your code here
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge