top

Search

C Tutorial

.

UpGrad

C Tutorial

Input and Output Functions in C

Input and output (I/O) in C programming handle data entering and leaving a program. The stdio.h header file provides essential functions like scanf() for input and printf() for output. Streams in C make I/O programming device-independent, enabling programmers to concentrate on data rather than specific sources or destinations. By using streams, programmers can seamlessly manage input streams (data entering the program) and output streams (data leaving the program). This abstraction simplifies handling I/O operations in C programs, ensuring flexibility and ease of use for different devices and data sources. 

What is input in C?

In the basic structure of C program, input refers to providing data or information to a program from an external source. Similar to how an ATM requires a user to input their PIN to perform transactions, algorithms in programming often require external data to operate effectively.

In C, input can be received from various sources, such as the command line or a file. When data is provided to a C program from an external location, it is stored in the computer's Random Access Memory (RAM), where the program can access and process it. This external data, essential for the program's execution, is input.

By accepting input, C programs can interact with users, process external data, and perform desired operations based on the provided information.

What is output in C?

In the basic structure of C program, input refers to providing data or information to a program from an external source. Imagine using an ATM where you enter your PIN and other required inputs. After following the instructions, the ATM provides cash, bank details, or other desired information. Similarly, algorithms use the input in programming to perform specific operations and generate the desired results.

After the algorithm processes the input, it produces output. The output can be presented in various ways, such as displaying it on the screen, printing it on a printer, or saving it to a disk. The purpose of output is to send the data from the program's memory to a specified location.

It's important to note that while input is necessary for many operations, there are cases where output can be generated without any specific input. For example, an algorithm designed to generate random numbers will produce random numbers as output without requiring specific input values.

How to take input and output of basic types in C?

To take input and output of basic types in C, you can use the scanf() function for input and the printf() function for output. Here's how you can do it:

Input:

To take input, use the scanf() function with the appropriate format specifier for the desired data type. The general syntax is:

scanf("%A", &variable);

Replace '%A' with the format specifier corresponding to the data type you want to input. '&' is used to get the address of the variable, allowing the input to modify its value.

Output:

To display output, use the printf() function with the appropriate format specifier for the desired data type. The general syntax is:

printf("%A", variable);

Replace '%A' with the format specifier corresponding to the data type you want to output. This function will print the value of the variable specified.

For example, for different basic data types where scanf is used for input and printf is used for output:

Integer - 
scanf("%d", &intVariable);
printf("%d", intVariable);

Float - 
scanf("%f", &floatVariable);
printf("%f", floatVariable);

Character - 
scanf("%c", &charVariable);
printf("%c", charVariable);

Input and Output Functions in C: Why do we use it?

We use input and output functions in C to enable communication between the program and the user or external devices. Here are some reasons why input and output functions are essential in C programming:

  • Interacting with the user: Input functions allow the program to receive data or information from the user. This enables user interaction and makes programs more dynamic and flexible. For example, a program may prompt the user for input to perform specific calculations or make decisions based on user preferences.

  • Processing external data: Input functions enable the program to read data from external sources, such as files or databases. This allows programs to work with large datasets, configuration files, or other external resources. The program can process this data, perform computations, or manipulate it as required.

  • Providing feedback and results: Output functions allow the program to display information or results to the user. This can include printing messages, displaying calculated values, or generating reports. Output functions help in conveying information and communicating the program's output effectively.

  • Debugging and troubleshooting: Input and output functions are valuable tools for debugging and troubleshooting programs. They allow developers to inspect the program's behaviour by printing intermediate values, checking variable states, or logging important information during program execution. This helps identify issues, understand program flow, and diagnose errors.

  • Integration with external devices: Input and output functions facilitate communication with external devices, such as printers, displays, or network interfaces. They provide a standardised way to send and receive data, enabling programs to interact with various hardware components and peripherals.

Types of Input and Output Functions in C

In the C programming language, input refers to providing data or information to a program, while output refers to displaying or writing the processed data. C provides a standard library that includes various functions to facilitate input and output operations.

There are two main types of input and output functions in C:

Formatted Functions

These functions allow data to be presented or accepted in a specific format. The most commonly used formatted input function is scanf(), which reads input from the user or external sources based on specified format specifiers. The printf() function is used for formatted output, allowing the program to display data in a desired format. These functions provide flexibility in handling different data types, such as integers, floating-point numbers, characters, etc.

Unformatted Functions

Unformatted functions are more basic and do not control data format during input or output operations. They are categorised into character functions and string functions. Character functions, such as getchar(), getche(), and getch(), are used for reading single characters from the input device (e.g., keyboard). On the other hand, putchar() and putch() are used for output, allowing the program to write single characters to the output source (e.g., screen). String functions, like fgets() and puts(), are commonly used for reading and writing strings of characters. These unformatted functions are simpler but provide the necessary functionality for basic input and output operations.

The C Standard Files

In the C language, all devices, including the screen and keyboard, are treated as files within a program. This means that when a program is executed, three files are automatically opened to provide access to the screen, keyboard, and standard error:

  • Standard output: Represented by the file pointer "stdout," this file allows the program to display output on the screen or any output device.

  • Standard input: Represented by the file pointer "stdin," this file enables the program to read input from the keyboard or any input source.

  • Standard error: Represented by the file pointer "stderr," this file is used for error messages and displays error-related output on the screen or the appropriate error output device.

The C language utilises file pointers to access and manipulate these files for reading and writing operations within a program. This abstraction allows for consistent input and output handling across different devices and facilitates efficient interaction with the user and error reporting.

The Format Specifiers

In C programming, format specifiers are used in functions like printf() and scanf() to specify the type of data being printed or read. These format specifiers inform the program about the expected data type. Here are some commonly used format specifiers and their corresponding data types:

Table showing data types and format specifiers

Showing Output with Printf() Function

The printf() function is commonly used in C programming to display output on the console. It is defined in the stdio.h header file. Programmers use printf() to print the values of variables or text sentences. Variables of different data types such as float, char, int, etc., can be printed using printf().

Examples of Printf()

  • Printing of a Sentence
#include <stdio.h>

int main() {
    printf("Hello, world! Welcome to the world of programming.");

    return 0;
}

Output: 

Hello, world! Welcome to the world of programming.
  • Printing of an Integer

#include <stdio.h>

int main() {
    int number = 42;

    printf("The number is: %d", number);

    return 0;
}

Output:

The number is: 42
  • Printing of a Character

#include <stdio.h>

int main() {
    char ch = 'A';

    printf("The character is: %c", ch);

    return 0;
}

Output:

The character is: A
  • Printing of Double and Float

#include <stdio.h>

int main() {
    double num1 = 3.14159;
    float num2 = 2.71828;

    printf("The value of num1 is: %lf\n", num1);
    printf("The value of num2 is: %f", num2);

    return 0;
}

Output: 

The value of num1 is: 3.141590
The value of num2 is: 2.718280
  • Printing of Multiple Outputs

#include <stdio.h>
int main() {
    int year = 1996;
    int month = 8;
    int day = 16;
    printf("Today's date is: %d-%d-%d", year, month, day);
    return 0;
}

Output: 

Today's date is 1996-8-16

Taking Input with Scanf() Function

The scanf() function in C receives inputs from the user. It allows the program to store the input values into variables of the appropriate data type.

In summary, the scanf() function receives inputs of various data types from the user. It is important to ensure that the variables used to store the input values match data types.

While efforts have been made to provide accurate and original responses, there may still be similarities with existing content. It is always recommended to verify and cross-reference the information provided.

Examples of Scanf()

  • Taking Input of Integer Value

#include <stdio.h>
int main() {
    int num; 
    printf("Enter an integer: ");
    scanf("%d", &num);
    
    printf("The entered integer is: %d", num);
    
    return 0;
}

Output:

Enter an integer: 25
The entered integer is: 25
  • Taking Input of Float Value

#include <stdio.h>

int main() {
    float num;
    
    printf("Enter a float value: ");
    scanf("%f", &num);
    
    printf("The entered float value is: %f", num);
    
    return 0;
}

Output: 

Enter a float value: 3.14
The entered float value is: 3.140000
  • Taking Input of Character Value

#include <stdio.h>

int main() {
    char ch;
    
    printf("Enter a character: ");
    scanf(" %c", &ch);
    
    printf("The entered character is: %c", ch);
    
    return 0;
}

Output:

Enter a character: A
The entered character is: A
  • Taking Input of Multiple Values

#include <stdio.h>

int main() {
    int num1, num2;
    
    printf("Enter two numbers separated by a space: ");
    scanf("%d %d", &num1, &num2);
    
    printf("The entered numbers are: %d and %d", num1, num2);
    
    return 0;
}

Output:

Enter two numbers separated by a space: 10 20
The entered numbers are: 10 and 20

Extra Information about Input-Output Functions

The scanf() function in C returns the total number of characters it reads, while the printf() function returns the number of characters that would have been printed if there were no errors during the output operation.

Here's an example illustrating the usage:

#include <stdio.h>

int main() {
    int x = printf("chocolate");
    
    printf("\nValue of x is: %d", x);
    
    return 0;
}

Output: 

chocolate Value of x is: 9

In the given program, the printf("chocolate") statement prints the word "chocolate" and returns the return value of printf(), which is 9. 

Input and Output Functions in C- Practice Problems

Here are some practice problems on input and output functions in C - 

Can you find the output obtained from the given program?

#include <stdio.h>

int main() {
    int num1 = 10;
    int num2 = 5;
    printf("The sum of %d and %d is: %d", num1, num2, num1 + num2);
    return 0;
}

Answer: The sum of 10 and 5 is: 15

What would be the resulting output of this program?

#include <stdio.h>

int main() {
    printf("Hello, World!");
    return 0;
}

Answer: Hello, World!

What would be the output obtained from the mentioned program?

#include <stdio.h>
int main() {
    float radius = 3.5;
    float area = 3.14159 * radius * radius;
    printf("The area of the circle with radius %.2f is: %.2f", radius, area);
    return 0;
}

Answer: The area of the circle with radius 3.50 is: 38.48

Conclusion

To sum up, input and output in C programming play a crucial role, enabling accurate communication and collaboration between the program, its users and external devices being used. Their standardised approach to handling data entering and leaving the program is what fuels programmers to create powerful, dynamic and versatile applications in the long run. 

While learning all about input and output functions in C through this tutorial can benefit you greatly, upskilling with upGrad courses like Full Stack Software Development Bootcamp can further help you develop and nurture in-demand development skills. With in-demand skills taught under the guidance of industry professionals, this course is made to transform learners into seasoned developers. 

Don’t forget to grab this amazing opportunity, enroll now!

FAQs

1. What is the purpose of fflush() function in C?

The function fflush() is C is utilised to clean the output buffer faced in a stream. At times when you wish to get the output to be displayed on screen immediately, this function helps enable that by immediately getting the buffered data cleared and written on the output. 

2. How to clear the input buffer?

In order to clear the input buffer, run the given code snippet -

int c;
while ((c = getchar()) != '\n' && c != EOF);

3. How to handle input errors when using scanf()?

In order to handle the input errors when using scanf(), make sure you assess its return value, which is the number of conversions successfully done. If the value is lower than the expected number of conversions, an error can be assumed. Clear the input buffer and prompt the user to enter the input one more time. This will lead to successful handling of an error when using scanf().

Leave a Reply

Your email address will not be published. Required fields are marked *