Our very own printf!

The printf function in C is a powerful tool for formatting and printing text. It allows you to output text with various formatting options. Here's a sample code demonstrating the use of printf with different format specifiers, including floating-point lengths:

#include <stdio.h>

int main() {
    // Integer formatting
    int integerVariable = 42;
    printf("Integer: %d\n", integerVariable);

    // Character formatting
    char charVariable = 'A';
    printf("Character: %c\n", charVariable);

    // String formatting
    char stringVariable[] = "Hello, printf!";
    printf("String: %s\n", stringVariable);

    // Floating-point formatting
    double doubleVariable = 3.14159;
    printf("Double: %f\n", doubleVariable);

    // Specifying precision for floating-point
    printf("Double with 2 decimal places: %.2f\n", doubleVariable);

    // Scientific notation for floating-point
    printf("Double in scientific notation: %e\n", doubleVariable);

    // Width and precision for floating-point
    printf("Double with width and precision: %10.3f\n", doubleVariable);

    // Printing in hexadecimal
    printf("Integer in hexadecimal: %x\n", integerVariable);

    // Printing in octal
    printf("Integer in octal: %o\n", integerVariable);

    // Printing the address of a variable
    printf("Address of integerVariable: %p\n", (void*)&integerVariable);

    // Printing a percentage sign
    printf("This is a percentage sign: %%\n");

    return 0;
}

To print pointers and unsigned values using printf in C, you can use the following format specifiers:

  1. Printing Pointers:

    • Use %p to print the pointer address.
  2. Printing Unsigned Values:

    • Use %u for unsigned int.

    • Use %lu for unsigned long.

    • Use %llu for unsigned long long.

Here's an example demonstrating how to print pointers and unsigned values:

#include <stdio.h>

int main() {
    int integerValue = -42;
    unsigned int unsignedIntValue = 42;
    unsigned long unsignedLongValue = 1234567890L;
    unsigned long long unsignedLongLongValue = 9876543210ULL;

    int *pointer = &integerValue;

    // Printing pointers
    printf("Pointer address: %p\n", (void*)pointer);

    // Printing unsigned values
    printf("Unsigned integer: %u\n", unsignedIntValue);
    printf("Unsigned long: %lu\n", unsignedLongValue);
    printf("Unsigned long long: %llu\n", unsignedLongLongValue);

    return 0;
}

In this example, %p is used to print the address stored in the pointer, and %u, %lu, and %llu are used for unsigned integer, unsigned long, and unsigned long long values, respectively. Make sure to cast the pointer to (void*) when using %p to avoid compiler warnings.