How to Use Conversion Characters in the C Language's printf() Function

In the C language, if you want to print the value of a variable to the screen, you'll likely use the printf() function. To do so, you need to include a conversion character — a placeholder of sorts — in the literal string that you want to print. That conversion character is then replaced by the variable or value you indicate later in the command.

Consider this example:

#include <stdio.h>
 int main()
{
    int age;
    float distance;
    age = 27;
    distance = 319.125;
    printf("The alien is %d years old and\n",age);
    printf("comes from a planet %f microns away.\n",distance);
    return(0);
}

This source code declares two variables — age and distance — and then assigns to them the values 27 and 319.125, respectively. In the printf() functions, the %d and %f in the statements' strings are conversion characters. This is a glimpse into the power of printf(); the %d and %f are replaced by an integer and a floating-point value (respectively) specificed later in the printf() functions' parentheses. In this case, the values to substitute are the variables age and distance.

Save this code, compile it, and run it, and you should see this:

The alien is 27 years old and comes from a planet 319.125 microns away.

You need to be sure that the conversion code you include in the string statement matches the number type that you assigned to the variable when you declared it or you might not be happy with the results. The following table lists the conversion codes in the C language:

Conversion Character Displays
%% The percent character, %
%c Single character (char) value
%d Integer (int, short int, long int) value
%e Floating-point (float or double) value in scientific notation with a little E
%E Floating-point (float or double) value in scientific notation with a big E
%f Floating-point (float or double) value in decimal notation
%g Either %f or %e is used, depending on which is shorter
%G Either %F or %E is used, depending on which is shorter
%i Integer (int, short int, long int) value
%o Unsigned octal value (no leading 0)
%p Memory location or address in hexadecimal (pointer)
%s String constant or variable (char *)
%u Unsigned integer (unsigned int, unsigned short int, unsigned long int) value
%x Unsigned hexadecimal value, lowercase a–f, no leading 0 or x
%X Unsigned hexadecimal value, uppercase A–F, no leading 0 or X
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com