HOME HTML EDITOR C JAVA PHP

C Output: Displaying Information

In C programming, output refers to the data that is sent from the program to the screen or any other output device. The printf() function is the most frequently used function for printing text, numbers, and variables to the console.

1. The printf() Function

The printf() function is part of the stdio.h library. It stands for "print formatted." To use it, you must include the standard input-output header file at the top of your code.

#include <stdio.h>

int main() {
    printf("Hello World!");
    return 0;
}

2. New Lines (\n)

By default, printf() does not insert a new line at the end of the output. If you use multiple printf() statements, they will appear on the same line. To move to a new line, use the \n escape sequence.

printf("Hello World!\n");
printf("I am learning C.");

3. Common Escape Sequences

Escape sequences are special characters used inside strings to represent things like tabs, new lines, or quotes.

Escape Sequence Description
\n Inserts a New Line.
\t Inserts a horizontal Tab space.
\\ Inserts a Backslash character.
\" Inserts a Double Quote character.

4. Printing Variables and Format Specifiers

To print variables (numbers or characters), you must use **Format Specifiers**. These tell the printf() function what type of data it is printing.

int myNum = 15;
char myLetter = 'D';

printf("My favorite number is %d\n", myNum);
printf("My grade is %c", myLetter);

5. Combining Text and Variables

You can mix plain text and format specifiers within a single printf() function. The values of the variables will be inserted at the position of the specifiers in the order they are listed.

int age = 25;
printf("I am %d years old.", age);

6. Formatting Decimal Precision

When printing floating-point numbers, C often prints many zeros after the decimal. You can control the precision by using a dot (.) followed by a number between the % and the f.

float myFloat = 3.14159;

printf("%f\n", myFloat); // Default (3.141590)
printf("%.2f\n", myFloat); // Prints 2 decimal places (3.14)
printf("%.4f\n", myFloat); // Prints 4 decimal places (3.1416)
Important: Always ensure that the number of format specifiers matches the number of variables you provide. If you have two %d specifiers but only one variable, the program will output random "garbage" data.