For working professionals
For fresh graduates
More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
Foreign Nationals
The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .
Recommended Programs
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
Think of any C program as a conversation. How does it talk to you, and how does it listen to your commands? The answer lies in the essential tools that manage all communication between you and your application.
These tools are the Input and Output Function in C. Functions like printf() act as the program's voice, displaying results and messages, while scanf() acts as its ears, receiving data from you. Mastering this fundamental Input and Output Function in C is the first step to creating interactive and useful programs. This tutorial will show you how to use these functions with practical examples and best practices.
Want to master more real-world C programming problems? Explore our Software Engineering Courses and boost your skills in C programming with hands-on practice.
Before, diving into the details of input and output function in C, you must understand three concepts, including:
These three are highly recommended from an expert’s perspective to quickly and efficiently understand I/O function in C.
Now, let’s see why use the Input and Output functions in C. I/O functions in C are mainly used to interact with the user, to take the data from the user, and provide the output, and the most important work the I/O function do is error handling.
Let’s discuss them in detail.
Ready to move beyond C programming and unlock new career opportunities? We've curated these forward-looking courses specifically to enhance your professional growth:
Interactivity with Users
The primary reason we use the input and output function in C is to enable programs to interact with users. Without these functions, programs would be purely static, incapable of receiving or displaying any meaningful data.
By utilizing input functions like scanf() or getchar(), a program can capture dynamic user input. Similarly, output functions like printf() allow the program to present information to the user in a readable format.
Must Explore: C Tutorial for Beginners: Learn C Programming Step-by-Step
Data Capture
Through input functions in C, we can capture user-entered data, which is crucial for making programs flexible and adaptive to different scenarios. For instance, an application that calculates taxes requires user input in the form of a salary or income. Without input functions, this would not be possible.
Data Presentation
Once the data is captured, the output functions in C allow us to present the results or process information for display. For example, after calculating a tax value, the result can be printed to the console for the user to see.
Error Handling
Input and output functions also play an essential role in error handling. If the user enters an incorrect value, the program can use output functions to display an error message, guiding the user to correct the mistake.
Must Read: 29 C Programming Projects in 2025 for All Levels [Source Code Included]
In C, input and output functions can be broadly categorized into standard input/output functions and file input/output functions. Each of these categories has specific functions designed for different tasks.
Standard I/O Functions
Standard I/O functions are used for interacting with the user via the console. These include functions like printf(), scanf(), getchar(), putchar(), etc., that allow you to capture input and display output in text form.
File I/O Functions
File I/O functions are used for reading from and writing to files. These functions, such as fopen(), fscanf(), fprintf(), and fclose(), allow a program to interact with external files and store or retrieve data.
Character I/O Functions
Character I/O functions are specifically used to handle individual characters. getchar() and putchar() are classic examples of character I/O functions that allow programs to read and write characters one at a time.
String I/O Functions
String I/O functions handle entire strings of characters. Functions like gets() and puts() fall into this category, enabling easy handling of user input and output as strings.
Here’s a quick summary of these categories and the functions within each:
I/O Type | Function(s) | Description |
Standard Input Functions | scanf(), getchar(), fscanf() | Functions to read input from the user or files. |
Standard Output Functions | printf(), putchar(), fprintf() | Functions to print output to the screen or to files. |
File Input Functions | fscanf(), fgets() | Functions to read data from files. |
File Output Functions | fprintf(), fputs() | Functions to write data to files. |
Character I/O Functions | getchar(), putchar() | Functions to handle input and output of a single character. |
String I/O Functions | gets(), puts() | Functions to handle entire strings of characters for input/output. |
Also Read: Static Function in C: Definition, Examples & Real-World Applications
In C programming, format specifiers are used in functions like printf() and scanf() to specify the type of data to be input or output. Below is a comprehensive table of commonly used format specifiers for various data types:
Specifier | Data Type | Description | Example |
%d | Integer (int) | Prints a signed decimal integer. | printf("%d", 123); // Output: 123 |
%i | Integer (int) | Similar to %d, used for signed decimal integers. | printf("%i", 123); // Output: 123 |
%u | Unsigned Integer (unsigned int) | Prints an unsigned decimal integer. | printf("%u", 123); // Output: 123 |
%f | Floating-point (float) | Prints a floating-point number (6 decimal places by default). | printf("%f", 3.14159); // Output: 3.141590 |
%lf | Double (double) | Prints a double precision floating-point number. | printf("%lf", 3.14159); // Output: 3.141590 |
%c | Character (char) | Prints a single character. | printf("%c", 'A'); // Output: A |
%s | String (char array) | Prints a string of characters (terminated by \0). | printf("%s", "Hello!"); // Output: Hello! |
%x | Hexadecimal (unsigned int) | Prints an unsigned integer in hexadecimal (lowercase). | printf("%x", 255); // Output: ff |
%X | Hexadecimal (unsigned int) | Prints an unsigned integer in hexadecimal (uppercase). | printf("%X", 255); // Output: FF |
%o | Octal (unsigned int) | Prints an unsigned integer in octal. | printf("%o", 255); // Output: 377 |
%p | Pointer (void *) | Prints the memory address of a pointer. | printf("%p", ptr); // Output: 0x7ffee11b (example address) |
%e | Floating-point (float) | Prints a floating-point number in scientific notation (lowercase). | printf("%e", 12345.6789); // Output: 1.234568e+04 |
%E | Floating-point (float) | Prints a floating-point number in scientific notation (uppercase). | printf("%E", 12345.6789); // Output: 1.234568E+04 |
%g | Floating-point (float/double) | Automatically chooses between %e or %f based on the value. | printf("%g", 12345.6789); // Output: 12345.7 |
%G | Floating-point (float/double) | Automatically chooses between %E or %f based on the value. | printf("%G", 12345.6789); // Output: 12345.7 |
%ld | Long Integer (long) | Prints a long integer. | printf("%ld", 1234567890L); // Output: 1234567890 |
%lld | Long Long Integer (long long) | Prints a long long integer. | printf("%lld", 123456789012345LL); // Output: 123456789012345 |
%lu | Unsigned Long (unsigned long) | Prints an unsigned long integer. | printf("%lu", 1234567890UL); // Output: 1234567890 |
%llu | Unsigned Long Long (unsigned long long) | Prints an unsigned long long integer. | printf("%llu", 123456789012345ULL); // Output: 123456789012345 |
Pursue DBA in Digital Leadership from Golden Gate University, San Francisco!
The printf() function is one of the most commonly used output functions in C. It allows you to print formatted text to the console.
Syntax:
printf("format_string", value1, value2, ...);
Code Example 1:
#include <stdio.h>
int main() {
int num = 42;
printf("The answer is: %d\n", num);
return 0;
}
Explanation:
Output:
The answer is: 42
Code Example 2:
#include <stdio.h>
int main() {
float pi = 3.14159;
printf("The value of pi is approximately: %.2f\n", pi);
return 0;
}
Explanation:
Output:
The value of pi is approximately: 3.14
The scanf() function is used to capture input from the user.
Syntax:
scanf("format_string", &variable);
Code Example 1:
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0;
}
Explanation:
Output:
Enter an integer: 42
You entered: 42
Code Example 2:
#include <stdio.h>
int main() {
float height;
printf("Enter your height in meters: ");
scanf("%f", &height);
printf("Your height is: %.2f meters\n", height);
return 0;
}
Explanation:
Output:
Enter your height in meters: 1.75
Your height is: 1.75 meters
For character-based input and output, we use getchar() and putchar().
Code Example 1:
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar(); // Input a character
printf("You entered: ");
putchar(ch); // Output the character
return 0;
}
Explanation:
Output:
Enter a character: A
You entered: A
Check out the Executive Diploma in Data Science & AI with IIIT-B!
Code Example 2:
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar(); // Capture input
printf("Character entered is: ");
putchar(ch); // Display the character
printf("\n"); // New line for clarity
return 0;
}
Explanation:
Output:
Enter a character: B
Character entered is: B
Similarly, you can use other input and output function in C by referring to the type of I/O function and format specifier table provided above.
User-Driven Applications
Any application requiring direct interaction from users relies on input and output function in C. For example, command-line tools or games use input functions to take commands from users and output functions to display results or updates.
Example: A simple to-do list program could take user input to add tasks and display them using printf().
Data Processing
In real-world applications like data processing systems, input and output function in C are used to read from and write to files, process data, and display the results. A weather monitoring system that collects data from sensors would use these functions to gather and present data to the user.
Example: A program could read the temperature from a file and display the average temperature using printf().
Database Interaction
For database-like applications, input and output function in C help capture and display data from users. A contact management system might store user data in a file and use input functions to receive data and output functions to display it.
Example: A simple contact book application could store contact details in a file and display them using output functions like printf().
Embedded Systems
Embedded systems often interact with physical devices such as sensors or controllers, where input and output function in C enable communication with the hardware. For instance, a system monitoring tool might read data from sensors and display real-time system statistics.
Example: A temperature monitoring system using an embedded device would take input from a temperature sensor and output the value to a display.
Mastering the Input and Output Function in C is the key to transforming your static code into an interactive application. These functions are the essential bridge between your program and the user, allowing you to receive data and display meaningful results.
By understanding how to use functions like printf() and scanf() effectively, you're not just learning syntax—you're learning how to make your programs communicate. Keep practicing with these foundational tools, and you'll be well-equipped to build any Input and Output Function in C-driven program with confidence.
The Input and Output Function in C serves as the essential bridge for communication between a program and its environment, which is typically the user or a file. Input functions, like scanf() and getchar(), are used to receive data from an external source (such as keyboard input) and store it in variables for the program to process. Output functions, like printf() and putchar(), are used to display results, messages, and errors to the user (usually on the console). Without these functions, a program would be an isolated black box, unable to interact with the outside world.
C programming defines three standard I/O streams that are automatically available to every program. These are stdin (standard input), which is the default source for input and is typically connected to the keyboard; stdout (standard output), which is the default destination for output and is usually the console or terminal; and stderr (standard error), which is the default destination for error messages, also typically the console. Functions like scanf() read from stdin, while printf() writes to stdout.
Formatted I/O functions, like printf() and scanf(), allow you to read and write data in specific formats. They use format specifiers (e.g., %d, %s) to interpret the data as integers, strings, etc. Unformatted I/O functions, like getchar(), putchar(), gets(), and puts(), work with data in its raw character form without any specific formatting. They are often simpler and faster for character or string-based I/O. Understanding when to use each type of Input and Output Function in C is key to efficient programming.
Format specifiers are crucial because they tell the I/O function how to interpret the data in memory. For printf(), a format specifier like %d tells the function to read a variable's value as an integer and display it as such. For scanf(), it tells the function to interpret the user's input as an integer and store it in an integer variable. Using the wrong specifier (e.g., trying to print a float with %d) leads to undefined behavior and will produce garbage output because the function will misinterpret the data's binary representation.
Both functions are used for output, but puts() is simpler and more specialized. puts() can only be used to print a string to the console, and it automatically appends a newline character (\n) at the end. printf(), on the other hand, is a much more powerful and versatile function that can print formatted output, including strings, integers, and floats, and it does not automatically add a newline unless you explicitly include \n. For simply printing a string with a newline, puts() is slightly more efficient.
The scanf() function is capable of reading multiple values from a single line of input by using multiple format specifiers in its format string. For example, scanf("%d %f", &my_int, &my_float); will expect the user to enter an integer, followed by a space, and then a float. It processes the input sequentially and assigns the values to the corresponding variable addresses. However, it is sensitive to the whitespace in the format string and the input, and it does not handle input errors gracefully, which is why it must be used with care.
While commonly taught to beginners, scanf() is notoriously problematic for several reasons. A major issue is that it often leaves the newline character (\n) in the input buffer after reading a number, which can be unintentionally picked up by the next input function, causing it to misbehave. It also has poor error handling; if a user enters text when a number is expected, the program can enter an infinite loop or exhibit other undefined behavior. Finally, it is inherently unsafe for reading strings as it doesn't have a built-in way to prevent buffer overflows.
The gets() function is extremely dangerous and has been removed from the C standard library. This is because it does not perform any bounds checking and will continue to read characters until a newline is found, which can easily lead to a buffer overflow—a major security vulnerability. fgets(), on the other hand, is the safe and recommended alternative. It allows you to specify the maximum number of characters to read, which reliably prevents buffer overflows and makes your code much more secure.
The scanf() function returns an integer value that represents the number of input items that were successfully read and assigned to variables. This return value is extremely useful for input validation. You can check if the return value of scanf() is equal to the number of items you were expecting to read. If it's not, you know that the user has entered invalid input, and you can handle the error gracefully instead of letting your program crash.
getchar() is a standard C library function (from <stdio.h>) that reads a single character from the standard input stream (stdin). It is a buffered function, which means it will wait for the user to press the Enter key before it processes the input. getch(), on the other hand, is a non-standard function (often found in <conio.h> on older compilers like Turbo C) that reads a single character directly from the keyboard as soon as it is pressed, without waiting for the Enter key. It is an unbuffered function, often used for creating more interactive console applications.
The fflush() function is used to "flush" or clear an output stream buffer. When you write data using a function like printf(), the data is often stored in a temporary buffer in memory before being sent to the final destination (like the console or a file). Calling fflush(stdout) forces any data in the standard output buffer to be written immediately. While it is defined for output streams, using it on an input stream (like fflush(stdin)) to clear the keyboard buffer is non-standard and not guaranteed to work across all compilers.
I/O redirection is a feature of command-line shells (like Bash on Linux) that allows you to change where a program's standard input comes from and where its standard output goes. For example, you can redirect the output of your C program to a file instead of the screen using the > operator: ./my_program > output.txt. Similarly, you can use a file as the input for your program instead of the keyboard using the < operator: ./my_program < input.txt.
Both printf() and fprintf() are used to write formatted output, but they differ in their destination. printf() is a specialized function that always writes to the standard output stream (stdout), which is typically the console. fprintf() is a more general function that can write to any file stream that you specify. The 'f' in fprintf stands for "file." You provide the file pointer as the first argument, for example: fprintf(my_file, "Hello, File!");.
File I/O in C is managed using a set of functions from the <stdio.h> library and a FILE pointer. The typical workflow is to first open a file using fopen(), which returns a FILE pointer. You must specify a mode, such as "r" for reading or "w" for writing. You then use functions like fscanf() or fgets() to read from the file, or fprintf() or fputs() to write to it. Finally, it is crucial to close the file using fclose() to release the resources.
Closing files with fclose() is an essential step in file handling for several reasons. First, it ensures that any data that has been buffered in memory by the output stream is flushed and physically written to the file on the disk, preventing data loss. Second, it releases the file handle and other resources that the operating system has allocated for the file. Forgetting to close files can lead to resource leaks, and on some systems, there is a limit to the number of files a program can have open simultaneously.
To use printf() effectively, always ensure that the format specifier (%d, %f, etc.) matches the data type of the variable you are printing to avoid undefined behavior. For floating-point numbers, you should control the precision using a specifier like %.2f to ensure consistent output. You can also use width and padding options (e.g., %10d) to align your output neatly in columns. Finally, remember to use escape sequences like \n for newlines and \t for tabs to format your text.
You can include special characters in your output by using escape sequences within your printf() format string. The most common ones are \n for a newline, \t for a horizontal tab, \\ to print a literal backslash, and \" to print a double quote. For input, functions like fgets() and getchar() will read these characters as part of the input stream, and you must handle them accordingly in your program's logic.
When you open a file with fopen(), you can specify the mode as text (e.g., "r", "w") or binary (e.g., "rb", "wb"). In text mode, the system may perform translations on the data, such as converting newline characters (\n) to the operating system's specific line ending sequence (like \r\n on Windows). In binary mode, no such translations are performed; the data is read and written exactly as is, byte for byte. Binary mode is essential for working with non-text files like images or executables.
The best way to master I/O in C is through a combination of structured learning and hands-on practice. A comprehensive program, like the software development courses offered by upGrad, can provide a strong foundation by explaining the theory and best practices. You should then apply this knowledge by building a variety of small projects that involve different types of I/O, such as a command-line calculator that takes user input, a program that reads and processes data from a text file, and a tool that writes formatted reports.
The key takeaway is that a solid understanding of the Input and Output Function in C is absolutely essential for creating any useful and interactive program. While functions like printf() and scanf() are easy to start with, a professional C programmer must also understand their limitations and know when to use more robust functions like fgets() and fprintf() for safe and reliable file and user I/O. Mastering these functions is a fundamental part of the journey to becoming a skilled C developer.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
FREE COURSES
Start Learning For Free
Author|900 articles published