Home » C Programming » Tutorial »
Formatted Input Output using printf() & scanf()
These two commonly used functions for Input/output and both are library function of C. The printf() prints on screen while scanf() is used to take input from standard input like keyboard.
The printf()Function
- The printf() function must be supplied with a string, followed by any values that are to be inserted into the string during printing. Syntax for printf : printf(string, expr1, expr2, ..);
- The format string may contain both ordinary characters and conversion specifications, which begin with the % character.
- A conversion specification is a placeholder representing a value to be filled in during printing.
- %d is used for int values
- %f is used for float values
- %c is used to char values
Example of printf() Function
#include int main() { int noX, noY; float xx, yy; noX = 17; noY = 19; xx = 37.1234f; yy = 777.0f; printf("noX = %d, noY = %d, xx = %f, yy = %f\n", noX, noY, xx, yy); return 0; }
Output :
noX = 17, noY = 19, xx = 37.123402, yy = 777.000000
Key points to remember about printf()
1. Compilers aren't required to check that the number of conversion specifications in a format string matches the number of output items.
2. Too many conversion specification doesn't give compiler error but we should take care of it -
3. Too few conversion specifications also doesn't give error but it should be taken care of -printf("%d %d \n", xx); Here only single "%d" should be used.
4. Compiler doesn't check for conversion specification. If the programmer uses wrong specification then the program's ouptut will be messed up - Suppose ii is int varaible and xx is char variable :printf("%d \n", ii, jj);
printf("%f %d ", ii, xx); /* in place of %d programmer put %f and inplace of %c programmer put %d */
The scanf() function
- scanf reads input according to a particular format.
- A scanf format string may contain both ordinary characters and conversion specifications.
- The conversions allowed with scanf are essentially the same as those used with printf.
- In many cases, a scanf format string will contain only conversion specifications: only conversion specifications
Example of scanf()
#include int main() { int noX; float noY; printf("\n Enter noX & noY - "); scanf("%d%f",&noX,&noY); printf("\n noX : %d, noY : %f", noX, noY); return 0; }
C Tutorial
- History of C Language
- The First Program in C
- Compilation & Execution
- Compile C on Dev-C++
- Compile C on GCC Linux
- Variable & Data types
- Comments
- Storage Classes
- Conidtional Statements
- Switch Cases
- Loops (for, while, do-while)
- Arrays
- Pointers
- Function Pointer
- Strings & Library func
- Formated I/O
- Structure
- Enum
- Union
- File I/O
- Memory Management
- Error Handling
- Type Casting