printf() in C - Source Code Example

In this source code example, we will see how to use the printf() function in C programming with an example.

Function Overview

The printf() function is one of the core functions in the C language for formatted output. Originating from the C standard library's <stdio.h>, it allows users to write data in various formats to the standard output. It employs format specifiers to achieve this versatility, ensuring that data from different variable types is displayed appropriately.

Source Code Example

#include <stdio.h>

int main() {
    // Basic usage
    printf("Hello, World!\n");

    // Integer formatting
    int age = 25;
    printf("Age: %d\n", age);

    // Double formatting with two decimal places
    double salary = 5000.50;
    printf("Salary: %.2lf\n", salary);

    // Character output
    char initial = 'A';
    printf("Initial: %c\n", initial);

    // String output
    char name[] = "Alice";
    printf("Name: %s\n", name);

    // Printing hexadecimal and octal values
    int hexValue = 255;
    printf("Hexadecimal: %x\n", hexValue);
    printf("Octal: %o\n", hexValue);

    // Printing a percent sign
    printf("100%% completed\n");

    return 0;
}

Output

Hello, World!
Age: 25
Salary: 5000.50
Initial: A
Name: Alice
Hexadecimal: ff
Octal: 377
100% completed

Explanation

In the provided source code example:

1. We start with a basic usage of printf() to output a string followed by a newline (\n).

2. We then delve into integer formatting using %d, displaying the age variable's value.

3. For floating-point numbers, we use %.2lf to display the salary with two decimal places.

4. The character variable initial is printed using the %c format specifier.

5. For printing strings, we use the %s format specifier.

6. Hexadecimal (%x) and octal (%o) format specifiers let us output the base representations of integers. Here, the integer 255 is represented as ff in hexadecimal and 377 in octal.

7. To print a percent sign itself, we use %%.

The versatility of the printf() function is evident from the variety of formats it supports. The format specifiers ensure that data is displayed appropriately for its type, making printf() an indispensable tool in C programming.====


Comments