C Input Output
C Input Output
C Output
In C programming, printf() is one of the main output function. The function sends
formatted output to the screen. For example,
Example 1: C Output
1. #include <stdio.h>
2. int main()
3. {
4. // Displays the string inside quotations
5. printf("C Programming");
6. return 0;
7. }
Output
C Programming
All valid C programs must contain the main() function. The code execution begins from
the start of the main() function.
The printf() is a library function to send formatted output to the screen. The function
prints the string inside quotations.
To use printf() in our program, we need to include stdio.h header file using #inclue
<stdio.h> statement.
The return 0; statement inside the main() function is the "Exit status" of the program.
It's optional.
To print float, we use %f format specifier. Similarly, we use %lf to print double values.
C Input
In C programming, scanf() is one of the commonly used function to take input from the
user. The scanf() function reads formatted input from the standard input such as
keyboards.
Example 5: Integer Input/Output
1. #include <stdio.h>
2. int main()
3. {
4. int testInteger;
5. printf("Enter an integer: ");
6. scanf("%d", &testInteger);
7. printf("Number = %d",testInteger);
8. return 0;
9. }
Output
Enter an integer: 4
Number = 4
Here, we have used %d format specifier inside the scanf() function to take int input
from the user. When the user enters an integer, it is stored in the testInteger variable.
Notice, that we have used &testInteger inside scanf(). It is
because &testInteger gets the address of testInteger, and the value entered by the
user is stored in that address.
When a character is entered by the user in the above program, the character itself is not
stored. Instead, an integer value (ASCII value) is stored.
And when we display that value using %c text format, the entered character is displayed.
If we use %d to display the character, it's ASCII value is printed.
Output
Enter a character: g
You entered g.
ASCII value is 103.
1. #include <stdio.h>
2. int main()
3. {
4. int a;
5. float b;
6.
7. printf("Enter integer and then a float: ");
8.
9. // Taking multiple inputs
10. scanf("%d%f", &a, &b);
11.
12. printf("You entered %d and %f", a, b);
13. return 0;
14. }
Output
Enter integer and then a float: -3
3.4
You entered -3 and 3.400000
%d for int
%f for float
%lf for double
%c for char
Here's a list of commonly used C data types and their format specifiers.
Data Type Format Specifier
Int %d
Char %c
Float %f
Double %lf
unsigned int %u
signed char %c
unsigned char %c