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.
#include <stdio.h>
int main(void) {
printf("Welcome to plus2net\n");
return 0;
}
Output
Welcome to plus2net
| Specifier | Typical use |
|---|---|
%d | signed int |
%u | unsigned int |
%f | floating-point output |
%c | character |
%s | string |
%ld | signed long |
%zu | size_t, commonly from sizeof |
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.
char ch = 'A';
char name[] = "plus2net";
printf("Character: %c\n", ch);
printf("String: %s\n", name);
Output
Character: A
String: plus2net
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.
printf("Line 1\nLine 2\n");
printf("Name\tScore\n");
\n starts a new line and \t inserts a horizontal tab.
char text[] = "plus2net";
printf("%c\n", text[3]);
printf("%c\n", text[4]);
Output
s
2
Array indexing starts at zero.
#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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Pratibha Suralkar | 25-09-2016 |
| what is the output of following : printf("%d",printf("welcome")); | |