Course Content
C Tutorial
About Lesson

Basic Input and Output

Input and output operations are fundamental in programming. In C, these operations involve the transfer of data between the program and external devices like the keyboard, screen, files, etc. It allows users to interact with programs by providing inputs and receiving outputs.

Standard Input and Output Functions

C provides standard input/output functions that facilitate communication between the program and the user or external devices. Some common functions include:

  • printf(): Used to display output on the screen/console.
  • scanf(): Facilitates input from the user via the keyboard.
  • getchar() and putchar(): Read and write a single character respectively.

printf() Function

The printf() the function is pivotal for output in C. It allows the programmer to display various types of data such as integers, characters, strings, and more in a formatted manner. For instance:

int num = 10;
printf("The value of num is: %d", num);

This would display: “The value of num is: 10” on the screen.

scanf() Function

Conversely, the scanf() function enables the program to receive inputs from the user. It reads input based on the specified format and stores the data into variables. For example:

int num;
printf("Enter a number: ");
scanf("%d", &num);

This prompts the user to enter a number, which is then stored in the variable num.

getchar() and putchar() Functions

getchar() reads a single character from the standard input (usually the keyboard), while putchar() writes a character to the standard output (usually the console). These functions can be used for basic character input and output operations.

File Input and Output in C

Apart from standard input/output, C also supports file handling. Functions like fopen(), fclose(), fscanf(), and fprintf() facilitate reading from and writing to files.

Best Practices for Input and Output in C

  1. Error Handling: Always validate user inputs to prevent errors or unexpected behavior in the program.
  2. Format Specifiers: Ensure the correct use of format specifiers (%d, %f, %c) in printf() and scanf() to match the data type being used.
  3. Buffer Flushing: Use fflush(stdin) to clear the input buffer if necessary, especially after using scanf()