Displaying Output in C
In C, you can display output to the console or terminal using the printf
function from the standard input/output library (stdio.h
). Here's a basic overview of how to use printf to display output in C:
#include
int main() {
// Displaying text
printf("Hello, World!\n");
// Displaying variables
int age = 25;
printf("My age is %d years old.\n", age);
// Displaying floating-point numbers
double pi = 3.14159;
printf("The value of pi is approximately %.2f\n", pi);
// Displaying characters
char grade = 'A';
printf("My grade is %c\n", grade);
// Displaying strings
char name[] = "John";
printf("My name is %s\n", name);
return 0;
}
In the above example:
-
printf
is used to print text and variables to the console.
-
You use format specifiers like
%d
, %f
, %c
, and %s
to indicate where and how the variables should be inserted into the output string.
-
\n
is used for a newline character to move to the next line after printing.
-
The format specifiers must match the type of the variables you're trying to print.
%d
is for integers, %f
for floating-point numbers, %c
for characters, and %s
for strings.
-
You can also include literal text within the double quotes in
printf
.
-
At the end of
main()
, return 0;
is used to indicate successful program execution, with 0 typically indicating success.
When you run this program, you'll see the output displayed in your console or terminal:
Hello, World!
My age is 25 years old.
The value of pi is approximately 3.14
My grade is A
My name is John
You can use printf to format and display a wide range of data types and text in your C programs, making it a powerful tool for communicating information to users or for debugging purposes.