Input and Output in C Language


Introduction

Input and output (I/O) operations are essential in programming, allowing programs to interact with users by accepting input and displaying output. In the C programming language, the printf and scanf functions are commonly used for these tasks. This article explains how to use printf and scanf for basic I/O in C.

The printf Function

The printf function is used to display output on the screen. It is part of the stdio.h library, which must be included at the beginning of your program to use printf. The general syntax of printf is:

printf("format string", argument_list);

The format string contains the text to be displayed along with format specifiers that determine how arguments are displayed. Some common format specifiers are:

  • %d - Integer
  • %f - Floating-point number
  • %c - Character
  • %s - String

Example of printf


This program will output: Your age is: 25.


The scanf Function

The scanf function is used to receive input from the user. Like printf, it is also part of the stdio.h library. The syntax for scanf is:

scanf("format string", &variable);

The format string in scanf specifies the type of data expected from the user. The & symbol (address-of operator) is used to pass the address of the variable where the input will be stored.

Example of scanf

In this program, the user is prompted to enter their age, and scanf stores the input in the age variable. printf then displays the entered age.

Using Multiple Format Specifiers

Both printf and scanf allow multiple format specifiers to handle various types of data. For example, we can prompt for both an integer and a floating-point number:

This program accepts both an integer (age) and a floating-point number (height), displaying them in a formatted output.

Conclusion

The printf and scanf functions are fundamental for input and output operations in C. They provide a flexible way to display text and receive user input. By mastering these functions, you can make your C programs interactive and user-friendly.






Advertisement