In C, basic input and output operations are performed using the stdio.h library, which stands for “standard input-output.” The two primary functions for basic input/output are printf for output and scanf for input.
1.Output with printf:
The printf function is used to display output on the console.
Example:
#include <stdio.h>
int main() {
printf(“Hello, World!n”);
return 0;
}In this example, the program prints “Hello, World!” to the console. The n represents a newline character, moving the cursor to the next line.
2. Input with scanf:
The scanf function is used to read input from the user.
Example:
#include <stdio.h>
int main() {
int age;
printf(“Enter your age: “);
scanf(“%d”, &age);
printf(“You entered: %dn”, age);
return 0;
}In this example, the program prompts the user to enter their age. The %d format specifier in scanf is used to read an integer, and &age represents the memory address of the age variable.
3. Formatted Output with printf:
printf allows formatting output using format specifiers.
Example:
#include <stdio.h>
int main() {
int num1 = 10;
double num2 = 3.14;
printf(“Integer: %d, Double: %fn”, num1, num2);
return 0;
}Here, %d and %f are format specifiers. They are placeholders for the actual values (num1 and num2), respectively.
4. Formatted Input with scanf:
scanf can also use format specifiers to read formatted input.
Example:
#include <stdio.h>
int main() {
int num1;
double num2;
printf(“Enter an integer and a double: “);
scanf(“%d %lf”, &num1, &num2);
printf(“Integer: %d, Double: %fn”, num1, num2);
return 0;
}Here, %d and %lf in scanf correspond to the expected input types, an integer and a double.