Inputs and Outputs in C Language:
Inputs and Outputs in C
C provides various functions for input and output operations. The most commonly used functions for this purpose are printf()
and scanf()
.
printf() Function
The printf()
function is used to print messages and values to the standard output (usually the console). Here are its main uses:
Printing a Message
To print a message, simply pass the message string to the printf()
function:
#include
int main() {
printf("Hello, World!\n");
return 0;
}
Printing a Value
To print a value, use a control string that specifies the type of the value and pass the value as an argument to the printf()
function:
#include
int main() {
int a = 5;
float b = 3.14;
char c = 'A';
printf("Integer: %d\n", a);
printf("Float: %.2f\n", b);
printf("Character: %c\n", c);
return 0;
}
Control Strings
Control strings are used to specify the type of the values to be printed. Here are some commonly used control strings:
Control String |
Type |
Description |
%d |
int |
Prints an integer |
%f |
float |
Prints a floating-point number |
%.2f |
float |
Prints a floating-point number with 2 decimal places |
%c |
char |
Prints a character |
%s |
char* |
Prints a string |
Escape Sequences
Escape sequences are used to represent special characters in a string. Here are some commonly used escape sequences:
Escape Sequence |
Description |
\\n |
Newline |
\\t |
Tab |
\\\\ |
Backslash |
\\\" |
Double quote |
\\' |
Single quote |
scanf() Function
The scanf()
function is used to read input from the standard input (usually the console). Here are its main uses:
Reading an Integer
#include
int main() {
int a;
printf("Enter an integer: ");
scanf("%d", &a);
printf("You entered: %d\n", a);
return 0;
}
Reading a Float
#include
int main() {
float b;
printf("Enter a float: ");
scanf("%f", &b);
printf("You entered: %.2f\n", b);
return 0;
}
Reading a Character
#include
int main() {
char c;
printf("Enter a character: ");
scanf(" %c", &c); // Note the space before %c to skip any whitespace
printf("You entered: %c\n", c);
return 0;
}
Reading a String
#include
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);
printf("You entered: %s\n", str);
return 0;
}
Examples
Here are some examples of using printf()
and scanf()
in a C program:
#include
int main() {
int a;
float b;
char c;
char str[100];
printf("Enter an integer: ");
scanf("%d", &a);
printf("You entered integer: %d\n", a);
printf("Enter a float: ");
scanf("%f", &b);
printf("You entered float: %.2f\n", b);
printf("Enter a character: ");
scanf(" %c", &c); // Note the space before %c to skip any whitespace
printf("You entered character: %c\n", c);
printf("Enter a string: ");
scanf("%s", str);
printf("You entered string: %s\n", str);
return 0;
}