C Programming
Unit 3: Input and Output
Conversion specifications and formatted/unformatted I/O functions in C.
I/O operation in C
C does not have built-in I/O statements. Instead, it provides input and output through
standard library functions declared in the header file <stdio.h>.
I/O functions in C are divided into two categories:
- Formatted I/O —
printf(),scanf(). - Unformatted I/O —
getchar(),putchar(),gets(),puts().
Conversion specifications
A conversion specification (or format specifier) tells printf() and scanf() the type
of data being read or written. It begins with % followed by a character.
| Specifier | Type |
|---|---|
%d | Signed integer |
%u | Unsigned integer |
%f | Float |
%lf | Double |
%c | Character |
%s | String |
%x | Hexadecimal integer |
%o | Octal integer |
%e | Scientific notation |
%% | Prints a literal % sign |
Width and precision can be specified, for example %5d, %.2f, %-10s.
Formatted I/O
printf()
printf() writes formatted output to the standard output (screen).
#include <stdio.h>
int main(void)
{
int age = 20;
float height = 5.75f;
printf("Age = %d, Height = %.2f\n", age, height);
return 0;
}
scanf()
scanf() reads formatted input from the standard input (keyboard). Variables are passed by
their address using the & operator.
#include <stdio.h>
int main(void)
{
int n;
float f;
printf("Enter an integer and a float: ");
scanf("%d %f", &n, &f);
printf("You entered %d and %.2f\n", n, f);
return 0;
}
Unformatted I/O
Unformatted I/O functions deal with one character or one string at a time without conversion specifications.
getchar() and putchar()
getchar()reads a single character from the keyboard.putchar()writes a single character to the screen.
#include <stdio.h>
int main(void)
{
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: ");
putchar(ch);
putchar('\n');
return 0;
}
gets() and puts()
gets()reads a string (until newline) from the keyboard.puts()writes a string to the screen followed by a newline.
#include <stdio.h>
int main(void)
{
char name[50];
printf("Enter your name: ");
gets(name);
puts("Hello,");
puts(name);
return 0;
}