How to use printf in c?

Using printf in C: A Comprehensive Guide

Introduction

The printf function is a fundamental part of the C programming language, used for printing formatted output to the console or file. It is a versatile tool that allows you to print data in a human-readable format, making it an essential component of any C program. In this article, we will delve into the world of printf and explore its various features, syntax, and best practices.

Basic Syntax

The basic syntax of printf is as follows:

printf(format, arguments);

  • format: This is the format string that defines the layout of the output. It should be a string of characters that starts with a % and ends with a .
  • arguments: These are the values that will be inserted into the format string.

Format Specifiers

Format specifiers are used to specify the type and width of the output. Here are some common format specifiers:

  • %d: Decimal integer
  • %f: Floating-point number
  • %s: String
  • %c: Character
  • %x: Hexadecimal integer
  • %X: Hexadecimal lowercase letter
  • %o: Octal integer
  • %O: Octal lowercase letter
  • %p: Pointer
  • %e: Exponential notation
  • %E: Exponential notation with fixed point
  • %g: General format
  • %G: General format with fixed point

Example 1: Printing a Decimal Integer

#include <stdio.h>

int main() {
int x = 10;
printf("%dn", x); // Output: 10
return 0;
}

In this example, we use the %d format specifier to print the decimal integer x.

Example 2: Printing a Floating-Point Number

#include <stdio.h>

int main() {
float x = 3.14;
printf("%.2fn", x); // Output: 3.14
return 0;
}

In this example, we use the %f format specifier to print the floating-point number x.

Example 3: Printing a String

#include <stdio.h>

int main() {
char str[] = "Hello, World!";
printf("%sn", str); // Output: Hello, World!
return 0;
}

In this example, we use the %s format specifier to print the string str.

Example 4: Printing a Character

#include <stdio.h>

int main() {
char c = 'A';
printf("%cn", c); // Output: A
return 0;
}

In this example, we use the %c format specifier to print the character c.

Example 5: Printing a Hexadecimal Integer

#include <stdio.h>

int main() {
unsigned int x = 0x12345678;
printf("%xn", x); // Output: 12345678
return 0;
}

In this example, we use the %x format specifier to print the hexadecimal integer x.

Example 6: Printing a Hexadecimal Lowercase Letter

#include <stdio.h>

int main() {
unsigned char x = 0x41;
printf("%Xn", x); // Output: 41
return 0;
}

In this example, we use the %X format specifier to print the hexadecimal lowercase letter x.

Example 7: Printing a Pointer


#include <stdio.h>

int main() {
int* p = &x;
printf("%pn", p); // Output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