printf() in C for Formatted Output

printf() writes formatted output to the standard output stream. It is declared in <stdio.h>. The format string can contain normal text, escape sequences such as \n, and conversion specifications such as %d or %f.

Basic printf() Example Top ↑

#include <stdio.h>

int main(void) {
    printf("Welcome to plus2net\n");
    return 0;
}

Output

Welcome to plus2net

Common Format Specifiers Top ↑

SpecifierTypical use
%dsigned int
%uunsigned int
%ffloating-point output
%ccharacter
%sstring
%ldsigned long
%zusize_t, commonly from sizeof

Integer and Floating-Point Output Top ↑

The complete program structure is already shown above, so the next examples focus on the changing declarations and printf() statements.

int count = 25;
double pi = 3.14159;

printf("Integer: %d\n", count);
printf("Float: %.2f\n", pi);

Output

Integer: 25
Float: 3.14

Key change: %.2f requests two digits after the decimal point. The // notes used throughout these examples are C comments.

Characters and Strings Top ↑

char ch = 'A';
char name[] = "plus2net";

printf("Character: %c\n", ch);
printf("String: %s\n", name);

Output

Character: A
String: plus2net

Field Width and Precision Top ↑

double number = 123.456;
printf("%10.2f\n", number);

Output

    123.46

10 is the minimum field width and .2 is the precision for this floating conversion.

Newline and Tab Escape Sequences Top ↑

printf("Line 1\nLine 2\n");
printf("Name\tScore\n");

\n starts a new line and \t inserts a horizontal tab.

Print Individual Characters from a String Top ↑

char text[] = "plus2net";
printf("%c\n", text[3]);
printf("%c\n", text[4]);

Output

s
2

Array indexing starts at zero.

Print a String in Reverse Top ↑

#include <stdio.h>
#include <string.h>

int main(void) {
    char text[] = "plus2net";
    size_t length = strlen(text);

    while (length > 0) {
        length--;
        printf("%c", text[length]);
    }
    printf("\n");
    return 0;
}

Output

ten2sulp

C is case-sensitive. The library function is named printf, not Printf.

Practice Top ↑

  1. Display the sum of two integers.
  2. Print a four-row growing star pattern.
  3. Print a floating value with three digits after the decimal point.




plus2net.com



Pratibha Suralkar

25-09-2016

what is the output of following :

printf("%d",printf("welcome"));



✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer