Input and Output in C


Introduction

Input and output are essential aspects of C programming. They allow you to interact with the user and display results. In this guide, we'll explore the basics of handling input and output in C, including functions like printf() and scanf(), and provide sample code to demonstrate their usage.


Printing Output with printf()

The printf() function is used to display output in C. It allows you to print formatted text to the standard output (usually the console). Here's an example:

#include <stdio.h>
int main() {
int age = 25;
printf("Hello, World!\\n");
printf("My age is %d years.\\n", age);
return 0;
}

In this example, we use printf() to display a greeting and the value of the age variable.


Reading Input with scanf()

The scanf() function is used to read input in C. It allows you to accept user input and store it in variables. Here's an example:

#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
printf("You entered: %d\\n", number);
return 0;
}

In this example, we use scanf() to prompt the user to enter an integer, and we store the input in the number variable.


Formatted Output

You can format the output using placeholders:

#include <stdio.h>
int main() {
double price = 12.345;
printf("The price is $%.2f\\n", price);
return 0;
}

In this example, we use the %.2f placeholder to format the output of the price variable with two decimal places.


Formatted Input

Formatted input with scanf() works similarly:

#include <stdio.h>
int main() {
int day, month, year;
printf("Enter a date (dd-mm-yyyy): ");
scanf("%d-%d-%d", &day, &month, &year);
printf("You entered: %02d-%02d-%d\\n", day, month, year);
return 0;
}

In this example, we use %02d to format the input date with leading zeros for day and month.


Conclusion

Input and output functions like printf() and scanf() are fundamental for interacting with users and displaying results in C programming. This guide has introduced you to the basics of handling input and output, including formatted input and output. As you continue your journey in C programming, you'll discover the power and flexibility of these functions for various tasks.