Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Jun 11, 2024
Difficulty: Easy

Printf and Scanf in C

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

In the world of programming, there are many ways to interact with users & take iinput from them. In the C programming language, two commonly used functions for this purpose are printf() & scanf(). These functions helps programmers to display output to the user & read input from the user respectively. 

Printf and Scanf in C

In this article, we will discuss both printf() & scanf() in detail, with examples to make you understand how they work properly.

printf() function

The printf() function is used to print formatted output to the console. It takes a string as its first argument, which can contain plain text & format specifiers. Format specifiers are special characters that begin with a percent sign (%) & are used to specify the type of data being printed.

Let’s look at the syntax of the printf() function:

printf("format string", argument1, argument2, ...);


The format string can contain plain text, escape sequences (like \n for a new line), & format specifiers. Each format specifier connected to an argument that follows the format string.

Some commonly used format specifiers are:

  • %d or %i for integers
     
  • %f for floating-point numbers
     
  • %c for characters
     
  • %s for strings

Example

  • C

C

#include <stdio.h>

int main() {

   int age = 25;

   printf("I am %d years old.\n", age);

   return 0;

}

Output

I am 25 years old.


In this example, the %d format specifier is used to print the value of the integer variable age. The \n escape sequence is used to move the cursor to a new line after printing the message.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

scanf() function

The scanf() function is used to read formatted input from the user via the console. It allows the program to pause & wait for the user to enter data. The scanf() function reads the input according to the format specifiers provided & stores the input in the corresponding variables.

Look at the general syntax of the scanf() function:

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

The format string in scanf() is similar to the one used in printf(). It specifies the type of data to be read. The variables that will store the input values are passed as arguments, each preceded by an ampersand (&) symbol, which denotes the address of the variable.

Example

  • C

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;

}

Output

Enter your age: 25
You are 25 years old.


In this example, the program prompts the user to enter their age using printf(). Then, it uses scanf() with the %d format specifier to read an integer value entered by the user. The input value is stored in the age variable. Finally, the program prints a message displaying the age entered by the user.

It's important to note that when using scanf(), you must provide the memory address of the variable where the input will be stored, hence the use of the & symbol before the variable name.

Program to print cube of given number:

Now let's combine the usage of printf() & scanf() to create a program that calculates & prints the cube of a number entered by the user.

  • C

C

#include <stdio.h>

int main() {

   int number, cube;

   printf("Enter a number: ");

   scanf("%d", &number);

   cube = number * number * number;

   printf("The cube of %d is %d.\n", number, cube);

   return 0;

}

Output

Enter a number: 5
The cube of 5 is 125.


In this code : 

  • We include the stdio.h header file to use printf() & scanf() functions.
     
  • We declare two integer variables: number to store the user's input & cube to store the calculated cube.
     
  • We use printf() to prompt the user to enter a number.
     
  • We use scanf() to read the integer input from the user & store it in the number variable.
     
  • We calculate the cube of the number by multiplying it by itself three times & store the result in the cube variable.
     
  • Finally, we use printf() to display the original number & its cube.

Program to print sum of 2 numbers:

Let's create another program that takes two numbers as input from the user, calculates their sum, & prints the result.

  • C

C

#include <stdio.h>

int main() {

   int num1, num2, sum;

   printf("Enter two numbers: ");

   scanf("%d %d", &num1, &num2);

   sum = num1 + num2;

   printf("The sum of %d and %d is %d.\n", num1, num2, sum);

   return 0;

}

Output

Enter two numbers: 10 20
The sum of 10 and 20 is 30.


In this code : 

  • We include the stdio.h header file to use printf() & scanf() functions.
     
  • We declare three integer variables: num1 & num2 to store the user's input, & sum to store the calculated sum.
     
  • We use printf() to prompt the user to enter two numbers.
     
  • We use scanf() to read two integer inputs from the user, separated by a space, & store them in the num1 & num2 variables respectively.
     
  • We calculate the sum of the two numbers by adding num1 & num2 & store the result in the sum variable.
     
  • Finally, we use printf() to display the original numbers & their sum.

Frequently Asked Questions

What if scanf() does not receive the expected data type?

If scanf() expects an integer (%d) and receives non-numeric input, it will result in an error, and the program may behave unpredictably. Always ensure the correct data type is entered.

Can printf() display different types of data in one statement?

Yes, printf() can handle multiple data types within the same statement. You can combine integers, floating-point numbers, and strings using appropriate format specifiers.

How to handle errors in input with scanf()?

To manage errors, check the return value of scanf(). It returns the number of items successfully read. If the return is less than expected, you may need to clear the input buffer and prompt the user again.

Conclusion

In this article, we talked about the printf() & scanf() functions in C programming. We discussed how printf() is used to display formatted output & how scanf() is used to read formatted input from the user. With the help of examples of these functions we learned how programs take input from the user & display output based on that respective input. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Topics covered
1.
Introduction
2.
printf() function
2.1.
Example
2.2.
C
3.
scanf() function
3.1.
Example
3.2.
C
4.
Program to print cube of given number:
4.1.
C
5.
Program to print sum of 2 numbers:
5.1.
C
6.
Frequently Asked Questions
6.1.
What if scanf() does not receive the expected data type?
6.2.
Can printf() display different types of data in one statement?
6.3.
How to handle errors in input with scanf()?
7.
Conclusion