Two commonly used functions for I/O (Input/Output) are
- printf()
- scanf()
The scanf() function reads formatted input from standard input (keyboard) whereas the printf() function sends formatted output to the standard output (screen).
🌲C output (="hello world")

🍀#include <stdio.h>
🍀int main()
🍀{
🍀 printf("C Programming");
🍀 return 0;
🍀}
-
All valid C program must contain the main() function. The code execution begins from the start of main() function.
-
The printf() is a library function to send formatted output to the screen. The printf() function is declared in "stdio.h" header file.
-
Here, stdio.h is a header file (standard input output header file) and #include is a preprocessor directive to paste the code from the header file when necessary. When the compiler encounters printf() function and doesn't find stdio.h header file, compiler shows error.
-
The return 0; statement is the "Exit status" of the program.
🌲integer output

🍀#include <stdio.h>
🍀int main()
🍀{
🍀 int testInteger = 5;
🍀 printf("Number = %d", testInteger);
🍀 return 0;
🍀}
- Inside the quotation of printf() function, there is a format string "%d" (for integer). If the format string matches the argument (testInteger in this case), it is displayed on the screen.
🌲integer input/output

🍀#include <stdio.h>
🍀int main()
🍀{
🍀 int testInteger;
🍀 printf("Enter an integer: ");
🍀 scanf("%d",&testInteger);
🍀 printf("Number = %d",testInteger);
🍀 return 0;
🍀}
🌲floats input/output

🍀#include <stdio.h>
🍀int main()
🍀{
🍀 float f;
🍀 printf("Enter a number: ");
🍀 scanf("%f",&f);
🍀 printf("Value = %f", f);
🍀 return 0;
🍀}
- The format string "%f" is used to read and display formatted in case of floats.
🌲character input/output

🍀#include <stdio.h>
🍀int main()
🍀{
🍀 char chr;
🍀 printf("Enter a character: ");
🍀 scanf("%c",&chr);
🍀 printf("You entered %c.",chr);
🍀 return 0;
🍀}
- Format string %c is used in case of character types.
🌲ASCII Code
-
When a character is entered in the above program, the character itself is not stored. Instead, a numeric value(ASCII value) is stored.
-
And when we displayed that value using "%c" text format, the entered character is displayed.

🍀#include <stdio.h>
🍀int main()
🍀{
🍀 char chr;
🍀 printf("Enter a character: ");
🍀 scanf("%c",&chr);
🍀 printf("You entered %c.\n",chr);
🍀 printf("ASCII value of %c is %d.", chr, chr);
🍀 return 0;
🍀}
🌲character input/output
reference: programiz
网友评论