Introduction to C Input and Output
In the C programming language, input and output (I/O) operations are essential for interacting with the user and displaying information. Two commonly used functions for I/O operations in C are printf
and scanf
. These functions allow you to read input from the user and display output on the screen.
The printf Function
The printf
function is used to display output on the screen. It allows you to print text, variables, and expressions. The syntax for printf
is:
printf("format string", arguments);
The format string
specifies the desired format for the output, and the arguments
are the values to be displayed. Here’s an example:
int age = 25; printf("I am %d years old.n", age);
In this example, the %d
is a format specifier for an integer. The value of the age
variable will be substituted in place of %d
when the printf
function is executed.
The n
is an escape sequence that represents a newline character, which moves the cursor to the next line.
The scanf Function
The scanf
function is used to read input from the user. It allows you to assign values to variables based on user input. The syntax for scanf
is:
scanf("format string", arguments);
The format string
specifies the expected format of the input, and the arguments
are the addresses of the variables where the input will be stored. Here’s an example:
int age; printf("Enter your age: "); scanf("%d", &age);
In this example, the %d
format specifier is used to read an integer from the user. The value entered by the user will be stored in the age
variable.
Note that the &
symbol is used before the variable name in the scanf
function to indicate the address of the variable.
Using printf and scanf Together
You can combine the printf
and scanf
functions to create interactive programs that display information and read input from the user. Here’s an example:
int num1, num2, sum; printf("Enter two numbers: "); scanf("%d %d", &num1, &num2); sum = num1 + num2; printf("The sum of %d and %d is %d.n", num1, num2, sum);
In this example, the user is prompted to enter two numbers. The scanf
function reads the input and stores the values in the num1
and num2
variables. The sum of the two numbers is then calculated and displayed using the printf
function.
The printf
and scanf
functions are fundamental for input and output operations in the C programming language. They allow you to interact with the user, display information, and read input. By understanding how to use these functions, you can create more interactive and dynamic programs.