Zone Of Makos

Menu icon

Input and Output statements in C

Introduction

In the C programming language, input and output (I/O) statements are used to interact with the user and perform input and output operations. These statements allow you to read data from the user and display output on the screen or write it to a file. Understanding I/O statements is crucial for creating interactive and user-friendly programs.

Standard Input and Output

C provides the concept of standard input ( stdin ), standard output ( stdout ), and standard error ( stderr ) streams for performing I/O operations:

1. Output Statements

To display output on the screen, you can use the printf function. It allows you to print formatted output by specifying format specifiers. For example:

int age = 25;
printf("I am %d years old.", age);

2. Input Statements

To read input from the user, you can use the scanf function. It allows you to read values of different datatypes by specifying format specifiers. For example:

int num;
scanf("%d", #);

File Input and Output

In addition to standard I/O, C also supports file I/O operations for reading from and writing to files:

1. Opening a File

To open a file, you can use the fopen function and specify the file path and the mode in which you want to open it (e.g., read, write, append). For example:

FILE* file = fopen("data.txt", "r");

2. Reading from a File

To read from a file, you can use functions like fscanf or fgetc . These functions allow you to read data from the file and store it in variables. For example:

int num;
fscanf(file, "%d", #);

3. Writing to a File

To write to a file, you can use functions like fprintf or fputc . These functions allow you to write data to the file. For example:

int num = 42;
fprintf(file, "%d", num);

4. Closing a File

After performing file operations, it is essential to close the file using the fclose function to release system resources. For example:

fclose(file);

Conclusion

Input and output statements are fundamental in C programming for interacting with the user and performing I/O operations. By mastering these statements, you can create programs that can read user input, display output, and work with files. Keep practicing and exploring different I/O functions and techniques to enhance the functionality and user experience of your C programs.