C Programming Tutorials : printf Format String

This post describes the use of Format String or Control String in printf function. An example of printf function is :
printf(" [FORMAT_STRING/CONTROL_STRING] ", arg1, arg2, ... );


Basic Structure of Format String or Control String in printf() Function:

% [FLAG] [WIDTH] . [PRECISION] [MODIFIER] [TYPE]

[FLAG]


- (minus)
Output is left-adjusted within the field. Remaining field will be blank.
If no used, output is right-adjusted within the field.

Works with: char, int , float, double, string.
+ (plus)
The sign of the numeric will be added before the numeric value i.e. if the numric value is positive, then a + sign will be added before the value.

Works with: int, float, double
Prints nothing with: char, string
0 (zero)
Causes leading zeros to appear.

Works with: string, int, float, double.
Prints nothing with:  char
#
(with o or x)
Causes octal and hex items to be preceded by 0 (zero) and 0x , respectively.

Works with:
( Octal )%#o
( Hex )%#x  or %#X
#
(with e, f or g)
Causes decimal point to be present in all floating point numbers.
Prevents the truncation of trailing zeros in g-type conversion.

Note: FLAGS can be mixed in any order

[WIDTH]


It is a +ve integer. It defines minimum field width.

Case 1: Length of data < [WIDTH]
        => Data is printed right-adjusted

Case 2: Length of data >= [WIDTH]
        => Entire data gets printed.

Note: If the [WIDTH] is given as -ve, then the - (minus) sign will be treated as flag


[PRECISION]


with String
Indicates no of charecters to be printed .
If [PRECISION] > Length of data, entire String gets printed
with float, double and  long double
Indicates no. of digits to be printed after decimal point.

If [PRECISION] < no. of digits after decimal point,
rounded value will be printed.

If [PRECISION] > no. of digits after decimal point,
trailing zeros will be added.
with integer
If [PRECISION] > Length of data,
prints (precision - length of data) no. of zeros.
with char
Does nothing

Note: [PRECISION] is a positive integer. If it is given as negative, then - (minus) sign + precision value + type gets printed.


[MODIFIERS]


h
for short integer
l
for long integers or double
L
for long double


[TYPE]


%a
Hexadecimal output in the form
0x h.hhhhhh p+ or - xxxx (C99 only)
%A
Hexadecimal output in the form
0x h.hhhhhh P+ or - xxxx (C99 only)
%x
Hexadecimal integer
e.g. 0x5fc8
%X
Hexadecimal integer
e.g. 0x5FC8
%o
Octal integer
e.g. 0879
%c
type char
e.g. 'a', 'A', '8' etc.
%d
decimal integer (signed )
e.g. 5, -4 etc.
%i
decimal integer (signed )
e.g. 6, -6 etc.
%u
unsigned decimal integer
etc. 5, 6 etc.
%s
String
e.g. "Do you like this article?" etc.
%e
scientific notation in the form
d.xxxxxx e + or - xxx
%E
scientific notation in the form
d.xxxxxx E + or - xxx
%f
float in the form d.xxxxxx
e.g. 5.000000
%g
uses %e or %f whichever is shorter
e.g. 100000, 1e+006, 0.0005, 5e-005 etc.
%G
uses %E or %f whichever is shorter
%p
Segment address (of pointer variable) in Hex.
e.g. 12ao
%Fp
Segment address and offset address in Hex.
e.g. 0001:00f2
%n
The associated argument must be a pointer to an integer. This specifier causes the number of charecters written (upto the point at which %n is entercounted) to be stored in that integer.
%%
prints a % sign


Note: [WIDTH] and [PRECISION] can be specified as a argument variable in printf() function. For example,
printf( "%*.*s" , width, precision );

Few Examples of printf() Function

Assume, the following variable declarations:
char str[]="world";
int a = 50;
int b = -50;
float c = 4.5446;
unsigned int d = 5;

Note: The following examples are Tested on 32 bit GCC compiler


Statements
Output
printf("%s", str);
printf("%-10s",str);
printf("%2s",str);
printf("%-2s",str);
printf("%(-10)s",str);
printf("%-(-10)s",str);
printf("%20(-10)s",str);
printf("%5s",str);
printf("%-5s",str);
printf("%+10s",str);
printf("%010s",str);
     world
world
world
world
(-10)s
(-10)s
(-10)s
world
world
     world
00000world
printf("%-10d",a);
printf("%+-10d",a);
printf("%010d",a);
printf("%0+10d",a);
printf("%+0+10d",a);
printf("%010d",b);
printf("%#d",a);

printf("%#x %x",a,a);
printf("%#o %o",a,a);

printf("%f",6);
printf("%f",6.);
printf("%f",6.0);
printf("%f");
printf("%d");
50
+50
0000000050
+000000050
+000000050
-000000050
50

0x32 32
062 62

0.000000
6.000000
6.000000
0.000000
garbage value
printf("%10.2s",str);
printf("%10.8s",str);
printf("%10.-4s",str);
printf("%1.-4s",str);

printf("%10.5f",c);
printf("%10.3f",c);
printf("%10.9f",c);
printf("%.5f",c);

printf("%4.3d",a);
printf("%.0d",a);

printf("%d %d", 5, -5);
printf("%i %i", 6, -6);
printf("%u %u", 7, -7);

printf("%5.3c",'d');
printf("%0c",'d');

printf("%I64");

printf("%s","Hello");
printf("%s","%d",5);

printf("I64d",5);
printf("%I64d",-5);

printf("%d"+1,5);
        wo
     world
-4s
-4s

4.54460
4.545
4.54600000
4.54460

050
50

5 -5
6 -6
7 4294967289

     d
d

prints nothing

Hello
%d

21474836485
25769803771

d


Confused, Have any questions?
Post your comments, questions, State your confusion to us.
We're here to help you.

Are you facing problems in writing C programs?
Hire us now!
Submit Your Problem Now

If You Enjoy This Post, Do us a favor: Share This Page


Subscribe via Email


Online C Programming Test

Test Description

Subject = C Programming
No of Questions = 20
Time = 30 mins
Total Marks = 20

Correct Answer = 1 mark
Wrong Answer = - 0.25 mark (negative)

C Program to find Armstrong Number

Definition of Armstrong Number:
A number is Armstrong if the sum of cubes of individual digits of a number is equal to the number itself.

Example:
0, 1, 153, 370, 371, 407 etc.

Explanation:
Let us take 153.
So, the sum of cubes of individual digits
= 13 + 53 + 33
= 1 + 125 + 27
= 153

Programming Approach (Algorithm):
Step 1: number = <Entered Number>
Step 2: Right Most Digit = number % 10
Step 3: number = number / 10
Step 4: Sum = Sum + Cube of Right Most Digit
Step 5: Repeat Step 2, 3 & 4 until number = 0
Step 6: if Sum = <Entered Number> then return 1
                                 // <Entered Number> is Armstrong number
        else return 0 // <Entered Number> is not an Armstrong number

C Program:
/*
 * PROGRAM NAME: Armstrong Number
 * SOURCE: http://CProgrammingOnline.blogspot.com
 */

/* HEADER FILE DECLARATION SECTION */
#include<stdio.h>

/* FUNCTION PROTOTYPE DECLARATION SECTION */
_Bool armstrong(int );

/* MAIN PROGRAM SECTION */
    int main(char* argv[], int argc){
    int number;    //Used to store the given number

    printf("\nProgram to Test Whether a Number is Armstrong Number or Not\n");
    printf("Enter an Integer Value (Max Size = %d bytes): ",sizeof(int));
    scanf("%d",&number);

    if(armstrong(number)==1){
        printf("\n%d is an armstrong number.",number);
    } else {
        printf("\n%d is not an armstrong number.",number);
    }
}

/*
 * FUNCTION SIGNATURE: _Bool armstrong(int );
 * INPUT: int number
 * OUTPUT: 1 if number(INPUT) is an armstrong number
 *         0 if number(INPUT) is not an armstrong number
 */
_Bool armstrong(int number){
    int stored_number = number;  //Used to Store the given number
    int sum = 0;                       //Used to Store the sum of digits
    char digit;                       //Used to Store the digits

    while(stored_number > 0){
        digit = stored_number % 10;
        sum += digit * digit * digit;
        stored_number /= 10;
    }

    if(sum == number){
        return 1;
    } else {
        return 0;
    }
}

Confused, Have any questions?
Post your comments, questions. State your confusion to us. We're here to help you.

Are you facing problems in writing C programs?
Hire us now!
Submit Your Problem Now

Subscribe via Email


Copy Text File using C Program


#include<stdio.h>

int main(int argc, char* argv[]){
    FILE *sfp;                   // Source File Pointer
    FILE *tfp;                   // Target File Pointer
    char SourceFilename[255];    // Stores the source file name
    char TargetFilename[255];    // stores the target file name
    char ch;                     // used to read charecter
                                 //       from source file name

    /* Get sourcefile name and targetfile name from the user */
    printf("\nEnter Soucefile Name: ");
    gets(SourceFilename);
    fflush(stdin);
    printf("Enter Targetfile Name (NOTE : If Targetfile already exists, its content will be overwritten): ");
    gets(TargetFilename);

    /* Open source file in read mode and target file in write mode */
    sfp=fopen(SourceFilename,"r");
    if(sfp==NULL){
        printf("\nERROR: Failed to open %s in read mode. Closing the program...",SourceFilename);
        return;
    }
    tfp=fopen(TargetFilename,"w");
    if(tfp==NULL){
        printf("\nERROR: Failed to open %s in write mode. Closing the program...",TargetFilename);
        return;
    }

    /* read charecter by charecter from sourcefile
       and write those charecters accordingly in targetfile */
    while(1){
        ch=fgetc(sfp);
        if(ch==EOF){
            break;
        }else{
            fputc(ch,tfp);
        }
    }

    /* close file pointers */
    fclose(sfp);
    fclose(tfp);
}