1: Understanding Standard Input and Output
In this lesson, we’ll delve into using standard input and output functions for reading and displaying data in C.
-
Standard Input Functions:
scanf()
: Used to read input from the standard input (keyboard).int age;
printf("Enter your age: ");
scanf("%d", &age); // Read an integer input
-
Standard Output Functions:
printf()
: Used to display output to the standard output (console).int num = 10;
printf("The number is: %dn", num); // Display an integer
2: Reading and Displaying Different Data Types
-
Reading Different Data Types:
- Use appropriate format specifiers with
scanf()
to read different data types.int num;
float price;
char initial;printf("Enter an integer: ");
scanf("%d", &num);printf("Enter a float: ");
scanf("%f", &price);printf("Enter a character: ");
scanf(" %c", &initial); // Note: Use a space before %c to consume any newline characters
- Use appropriate format specifiers with
-
Displaying Different Data Types:
- Use format specifiers with
printf()
to display various data types.int age = 30;
float height = 5.9;
char grade = 'A';printf("Age: %dn", age);
printf("Height: %.2f feetn", height); // Display float with 2 decimal places
printf("Grade: %cn", grade);
- Use format specifiers with
3: Formatting Output
-
Formatting Output:
- Use formatting options in
printf()
to control the appearance of output.int num = 12345;
printf("Number: %dn", num); // Default formatting
printf("Number: %10dn", num); // Right-aligned within a field width of 10
printf("Number: %-10dn", num); // Left-aligned within a field width of 10
printf("Number: %010dn", num); // Zero-padded with a field width of 10
- Use formatting options in
-
Formatting Floats:
- Control precision and width for floating-point numbers.
float pi = 3.14159;
printf("Pi: %fn", pi); // Default precision
printf("Pi: %.2fn", pi); // Display with 2 decimal places
printf("Pi: %10.2fn", pi); // Right-aligned within a field width of 10
- Control precision and width for floating-point numbers.
4: Practice and Examples
- Practice Exercise:
- Write a program that reads two integers from the user and displays their sum and product.
- Use appropriate input and output functions with proper formatting.
int main() {
int num1, num2;
printf("Enter first integer: ");
scanf("%d", &num1);
printf("Enter second integer: ");
scanf("%d", &num2);
int sum = num1 + num2;
int product = num1 * num2;
printf("Sum: %dn", sum);
printf("Product: %dn", product);
return 0;
}