C Input Output

In the C programming language, input and output (I/O) operations play a crucial role in allowing the user to interact with a program. This interaction can be in the form of reading data from the user, displaying output to the user, or reading and writing data to and from a file. In this article, we'll take a closer look at how I/O operations are performed in C and provide some practical examples to help illustrate the concepts.

Standard Input and Output in C

In C, the standard I/O functions are used for reading from and writing to the standard input and output devices, respectively. These devices are typically the keyboard for input and the screen for output. The standard I/O functions in C include printf() for output and scanf() for input.

Reading input from the user using scanf()

1#include <stdio.h> 2 3int main(void) { 4 int num; 5 printf("Enter a number: "); 6 scanf("%d", &num); 7 printf("You entered %d.\n", num); 8 return 0; 9}

In the above example, scanf() is used to read an integer value from the user and store it in the variable num. The format string "%d" specifies that an integer value should be read. The & symbol is used to pass the address of the num variable to scanf() so that it can store the value read from the user in that location.

Writing output to the screen using printf()

1#include <stdio.h> 2 3int main(void) { 4 int num = 42; 5 printf("The value of num is %d.\n", num); 6 return 0; 7}

In this example, printf() is used to write a string of text and the value of the num variable to the standard output device. The format string "The value of num is %d.\n" specifies that an integer value should be printed in place of the %d placeholder.