
Input and Output Functions in C
Understanding how to take input and display output is fundamental in C programming.
"In C programming, input functions allow user interaction, while output functions help in displaying meaningful results."
Standard Input and Output Functions
1. printf()
- Output Function
The printf()
function is used to print output to the console.
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
2. scanf()
- Input Function
The scanf()
function is used to take user input.
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("Your age is: %d\n", age);
return 0;
}
Formatted Input and Output
Format specifiers are used in printf()
and scanf()
to specify the type of data.
Format Specifier | Data Type | Example |
---|---|---|
%d |
Integer | int num = 10; |
%f |
Floating-point | float pi = 3.14; |
%c |
Character | char letter = 'A'; |
%s |
String | char name[20] = "Alice"; |
Other Input and Output Functions
1. gets()
and puts()
gets()
is used for taking a string input, while puts()
prints a string.
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
gets(name);
puts("Hello, ");
puts(name);
return 0;
}
2. fgets()
and fputs()
fgets()
is a safer alternative to gets()
, and fputs()
prints a string.
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
fputs("Hello, ", stdout);
fputs(name, stdout);
return 0;
}
3. getchar()
and putchar()
getchar()
reads a single character, while putchar()
prints a single character.
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: ");
putchar(ch);
return 0;
}
Why Use Different I/O Functions?
printf()
andscanf()
- Used for basic input and output.puts()
andgets()
- Used for handling strings.fgets()
andfputs()
- Safer alternatives for handling strings.getchar()
andputchar()
- Used for single character input/output.
Mastering input and output functions in C will help you develop interactive and user-friendly programs! 🚀