Menu
Coddy logo textTech

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:

  • %d for integers
  • %f for floats
  • %lf for doubles
  • %c for characters
  • %s for 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 icon

Challenge

Easy

Write a C program that does the following:

  1. Declare an integer variable num1 and a float variable num2.
  2. Use scanf() to read an integer value into num1 and a float value into num2 from the user.
  3. Calculate the sum of num1 and num2 and store it in a variable called sum.
  4. Print the values of num1, num2, and sum using printf(). Print num2 and sum with exactly 2 decimal places using the %.2f format 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.14

Cheat sheet

The scanf() function reads formatted input from the user. It requires <stdio.h>.

Basic syntax:

scanf("format string", &variable1, &variable2, ...);

Common format specifiers:

  • %d for integers
  • %f for floats
  • %lf for doubles
  • %c for characters
  • %s for strings

Use the ampersand (&) before variable names to provide the memory address:

int age;
scanf("%d", &age);

Try it yourself

#include <stdio.h>

int main() {
    // Declare your variables here
    
    // Your code here
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals