Unlocking the Power of C Programming: Output and Input Functions
Mastering C Output: The printf() Function
When it comes to C programming, the printf()
function is the star of the show. This powerful function sends formatted output to the screen, making it an essential tool for any programmer. But how does it work?
Let’s dive into an example. A valid C program must contain the main()
function, where code execution begins. Within this function, printf()
is used to print a string inside quotations. To utilize printf()
, we need to include the stdio.h
header file using the #include <stdio.h>
statement.
Example 1: Printing a Simple Message
The return 0;
statement inside the main()
function is the “Exit status” of the program, indicating its successful execution. This statement is optional, but it’s a good practice to include it.
Printing Variables: Using Format Specifiers
To print variables, we use format specifiers such as %d
for integers, %f
for floats, and %lf
for doubles. Let’s explore some examples:
Example 2: Printing an Integer
In this example, the %d
inside the quotations is replaced by the value of testInteger
.
Example 3: Printing Float and Double Values
To print float and double values, we use %f
and %lf
format specifiers, respectively.
Example 4: Printing Characters
When printing characters, we use the %c
format specifier.
C Input: The scanf() Function
While printf()
is used for output, scanf()
is a commonly used function for taking input from the user. This function reads formatted input from the standard input, such as keyboards.
Example 5: Taking Integer Input
Here, we use the %d
format specifier inside the scanf()
function to take an integer input from the user. The value entered by the user is stored in the testInteger
variable. Notice the use of &testInteger
inside scanf()
, which gets the address of testInteger
and stores the input value.
Example 6: Taking Float and Double Input
We use %f
and %lf
format specifiers for float and double inputs, respectively.
Example 7: Character Input and Output
When a character is entered by the user, its ASCII value is stored instead of the character itself. When we display this value using the %c
format specifier, the entered character is displayed. If we use %d
to display the character, its ASCII value is printed.
Example 8: Taking Multiple Inputs and Displaying Them
This example demonstrates how to take multiple inputs from the user and display them.
Format Specifiers for I/O: A Quick Reference
As seen in the examples above, we use:
%d
for integers%f
for floats%lf
for doubles%c
for characters
Here’s a list of commonly used C data types and their format specifiers:
…