How to take Input/Output in C Programming?
The two important functions printf and scanf are used in the C programming language to perform output and input operations. Let's understand both in detail with examples.
Note: We need to include <stdio.h> header file at the top because both input and output functions are present inside this header file. (alert-success)
printf function.
The printf function is used for formatted output in C. It allows you to print text and values to the console in a specific format.
Example Code:
//C Program to show the working of printf function #include <stdio.h> int main() { int age = 25; float height = 5.9; char name[] = "John Doe"; // Printing variables with format specifiers printf("Name: %s\n", name); printf("Age: %d\n", age); printf("Height: %.2f\n", height); return 0; }
Name: John Doe
Age: 25
Height: 5.90
In this example, the printf function is used to print the name, age, and height of a person using format specifiers. %s is used for strings, %d for integers, and %.2f for floating-point numbers with two decimal places.
scanf function.
The scanf function is used for formatted input in C. It allows you to read values from the user or a file based on the specified format.
Example Code:
//C Program to take input from user #include <stdio.h> int main() { char name[50]; int age; // Reading input from the user with format specifiers printf("Enter your name: "); scanf("%s", name); printf("Enter your age: "); scanf("%d", &age); // Displaying the input values printf("Name: %s\n", name); printf("Age: %d\n", age); return 0; }
Enter your name: Algolesson
Enter your age: 5
Name: Algolesson
Age: 5
In this example, the scanf function is used to read the name and age of the user from the console using format specifiers %s and %d, respectively. Note that for reading integers, we need to pass the memory address of the variable using the & (address-of) operator.
Format Specifiers.
We notice that format specifiers are something that we should know. In C programming, format specifiers are used with input/output functions like printf and scanf to specify the data type and format of the variables being printed or read.
List of Format Specifiers in C Program.
- %d : Used for integers (decimal format).
- %ld : Used for long integers.
- %u : Used for unsigned integers.
- %f : Used for floating-point numbers (decimal notation).
- %lf : Used for double-precision floating-point numbers.
- %c : Used for characters.
- %s : Used for strings (arrays of characters).
- %x : Used for hexadecimal (lowercase letters).
- %X : Used for hexadecimal (uppercase letters).
- %o : Used for octal numbers.
- %% : Used to print a literal % character (escape sequence).
Note: Some format specifiers have variations for different data types, such as %lld for long long integers, %hu for unsigned short integers, etc. (alert-success)
No comments:
Post a Comment