Learn C - C Console Output






To show message on console using C, use printf() to write message on console.

printf() can be passed parameters inside using %d for integer numeric and %f for floating numeric.

For char data type, we can use %c for passing parameter.

Here is a sample code


  #include <stdio.h> 
// w  w w  .  j  a va  2 s.  c o  m
  int main() { 
     int n = 10; 
     float m = 1.875; 
     char c =  'A '; 

     printf("%d \n",n); 
     printf("%f \n",m); 
     printf("% .2f \n",m); 
     printf("% .3f \n",m); 
     printf("%c \n",c); 
      
     return 0; 
  } 

The code above generates the following result.





Note

You can see on %f that wrote floating data with 6 decimal digits.

You can specify the number of decimal digit by passing numeric after dot (.), for instance, %.2f and %.3f.


//some floating-point combinations
#include <stdio.h>
//from  w  w  w .  ja v a 2 s .  co m
int main(void)
{
    const double RENT = 1234.99;  // const-style constant
    
    printf("*%f*\n", RENT);
    printf("*%e*\n", RENT);
    printf("*%4.2f*\n", RENT);
    printf("*%3.1f*\n", RENT);
    printf("*%10.3f*\n", RENT);
    printf("*%10.3E*\n", RENT);
    printf("*%+4.2f*\n", RENT);
    printf("*%010.2f*\n", RENT);
    
    return 0;
}

The code above generates the following result.





printf format

The prototype of the printf() function is:

int printf_s(char *format, . . .);

The first parameter is the format control string. The argument for this parameter is usually passed to the function as an explicit string constant.

The optional arguments to the function are the values to be output in sequence. They must correspond in number and type with the format conversion specifiers.

The following table shows how the optional output flag characters affect the output.

CharacterUse
+Ensures there's always a plus or minus sign preceding a signed output value. Only negative values have a sign by default.
-Specifies that the output value is left justified and padded with blanks on the right. The default positioning of the output is right justified.
0Specifies that integer or floating point values should be padded with zeros instead of spaces to fill out the field width to the left.
#Ensures that: 0 is to precede an octal output value, 0x or 0X is to precede a hexadecimal output value, a floating-point output value will contain a decimal point, for g or G floating-point conversion characters, trailing zeros will not be omitted.
SpaceSpecifies that positive or zero values are preceded by a space rather than a plus sign.

The optional field_width specifies the minimum field width for the output value.

If the value requires more characters, the field is simply expanded.

If it requires less than the minimum specified, it is padded with blanks, unless the field width is preceded by the 0 flag.

The optional precision specifier is generally used with floating-point output values and consists of a period followed by an integer.

A specifier of .n indicates that n decimal places are to be output for a floating-point value.

If the value to be output has more than n significant digits, it's rounded.

If you use it for integer conversions, it specifies the minimum number of digits to appear in the output.

Field Size

The optional size flags are shown in the following Table.

FlagEffect
hA following integer conversion specifier applies to a short or unsigned short argument.
hhA following integer conversion specifier applies to a signed char or unsigned char argument.
lA following integer conversion specifier applies to a long or unsigned long argument.
llA following integer conversion specifier applies to a long long or unsigned long long argument.
jA following integer conversion specifier applies to an intmax_t or uintmax_t argument.
zA following integer conversion specifier applies to a size_t argument.
tA following integer conversion specifier applies to a ptrdiff_t argument.
LA following floating-point conversion specifier applies to a long double argument.

You can use an h prefix for short types.

%hd displays a short integer in decimal form, and %ho displays a short integer

Therefore, h and l prefixes can be used with u for unsigned types.

For instance, in octal form.

Both the %lu notation for printing unsigned long types.


#include <stdio.h> 
int main(void) 
{ /*from  w ww  .j a  v  a 2  s .co m*/
    unsigned int un = 3000000000; /* system with 32-bit int */ 
    short end = 200;              /* and 16-bit short       */ 
    long big = 65537; 
    long long verybig = 12345678908642; 
 
    printf("un = %u and not %d\n", un, un); 
    printf("end = %hd and %d\n", end, end); 
    printf("big = %ld and not %hd\n", big, big); 
    printf("verybig= %lld and not %ld\n", verybig, verybig); 
 
    return 0; 
}    

The code above generates the following result.

Conversion Characters for integers

The following table lists the Conversion Characters in an Output Specification for integers:

Conversion characterOutput produced
d or iSigned decimal integer
oUnsigned octal integer
uUnsigned decimal integer
xUnsigned hexadecimal integer with lowercase hexadecimal digits a, b, c, d, e, f
XAs x but with uppercase hexadecimal digits A, B, C, D, E, F

The following code displays code number for a character


#include <stdio.h> 
int main(void) 
{ //from w w  w . j a  va2s . com
    char ch; 
 
    printf("Please enter a character.\n"); 
    scanf("%c", &ch);   /* user inputs character */ 
    printf("The code for %c is %d.\n", ch, ch); 
 
    return 0; 
}    

The code above generates the following result.

Conversion Characters floating-point

The following table lists the Conversion Characters in an Output Specification for floating-point:

Conversion characterOutput produced
f or FSigned decimal value
eSigned decimal value with exponent
EAs e but with E for exponent instead of e
gAs e or f depending on size of value and precision
GAs g but with E for exponent values
a or APresents a double value in hexadecimal form with the hexadecimal value preceded by 0x or 0X and any exponent prefixed with p or P.

The following table lists the Conversion Characters in an Output Specification for pointers:

Conversion characterOutput produced
pOutput the value as a pointer.

The following table lists the Conversion Characters in an Output Specification for characters:

Conversion characterOutput produced
cSingle character or precision characters
sAll characters until '\0' is reached or precision characters have been output

#include <stdio.h>
int main(void)
{
    printf("%x %X %#x\n", 31, 31, 31);
    printf("**%d**% d**% d**\n", 42, 42, -42);
    printf("**%5d**%5.3d**%05d**%05.3d**\n", 6, 6, 6, 6);
    
    return 0;
}

The code above generates the following result.

Escape Sequences

You can include whitespace characters in the format control string for printf().

Whitespace characters are the newline, carriage return, form-feed, space, and tab.

Some of these are represented by escape sequences and these are shown in the following Table.

Escape sequenceDescription
\bBackspace
\fForm-feed or page eject
\nNewline
\rCarriage return (for printers) or move to the beginning of the current line for output to the screen
\tHorizontal tab

You use the escape sequence \\ to output the backslash character, \.

To write a % character to stdout, you use %%.

Integer Output

Let's try a sample of integer output formats first.


#include <stdio.h> 
  /*from   w w  w  . j  a  v  a 2s .  c o m*/
int main(void) 
{ 
  int        i = 15,       j = 123,            k = 4567; 
  long long li = 56789LL, lj = 12345678901LL, lk = 23456789LL; 
  
  printf("i = %d   j = %d    k = %d   i = %6.3d   j = %6.3d   k = %6.3d\n", 
         i ,j, k, i, j, k); 
  printf("i = %-d   j = %+d   k = %-d   i = %-6.3d   j = %-6.3d   k = %-6.3d\n",
         i ,j, k, i, j, k); 
  printf("li = %d   lj = %d   lk = %d\n", li, lj, lk); 
  printf("li = %lld   lj = %lld   lk = %lld\n", li, lj, lk); 
  return 0; 
} 

The code above generates the following result.

Padding

The following example shows the padding and width control.


#include <stdio.h> 
/*w  w  w. java  2  s . c o  m*/
int main(void) 
{ 
  int k = 678; 

  // Display formats as heading then display the values 
  printf("%%d   %%o   %%x   %%X\n"); 
  printf("%d  %o  %x  %X\n", k, k, k, k ); 
  printf("\n|%%8d       |%%-8d      |%%+8d      |%%08d      |%%-+8d     |\n"); 
  printf("|%8d  |%-8d  |%+8d  |%08d  |%-+8d  |\n", k, k, k, k, k ); 
  return 0; 
} 

The code above generates the following result.

Outputting Floating-Point Values

The following code shows the the floating-point output options.


    #include <stdio.h> 
      /* ww  w  .  ja v a 2s.c o  m*/
    int main(void)     { 
      float  fp1 = 345.678f,    fp2 = 1.234E6f; 
      double fp3 = 234567898.0, fp4 = 11.22334455e-6; 
      
      printf("%f  %+f  %-10.4f  %6.4f\n", fp1, fp2, fp1, fp2); 
      printf("%e  %+E\n", fp1, fp2); 
      printf("%f  %g  %#+f  %8.4f  %10.4g\n", fp3,fp3, fp3, fp3, fp4); 
      return 0; 
    } 

The code above generates the following result.

Character Output

printf() has two options for character data: %c for single characters and %s for strings.

%lc and %ls are used to output wide characters.


    #include <stdio.h> 
    #include <limits.h>               // For CHAR_MAX 
    #include <ctype.h>                // For isprint() 
      /*ww  w  .ja  v a2  s .c  o m*/
    int main(void) 
    { 
      int count = 0; 
      
      printf("The printable characters are the following:\n"); 
      // Iterate over all values of type char 
      for(int code = 0 ; code <= CHAR_MAX ; ++code) 
      { 
        char ch = (char)code; 
        if(isprint(ch)) { 
          if(count++ % 32 == 0) 
            printf("\n"); 
          printf(" %c", ch); 
        } 
      } 
      printf("\n"); 
      return 0; 
    } 

The code above generates the following result.

Example

The following code shows how to print long strings.


/*  w  w  w . j a  v  a2  s . c  o  m*/
#include <stdio.h>
int main(void)
{
    printf("Here's one way to print a ");
    printf("long string.\n");
    printf("Here's another way to print a \
long string.\n");
    printf("Here's the newest way to print a "
           "long string.\n");      /* ANSI C */
    
    return 0;
}

The code above generates the following result.

Example 2

printf() returns the number of characters it printed.


#include <stdio.h> 
int main(void) 
{ /*from  w  ww.j ava 2s  .  c o  m*/
    int bph2o = 212; 
    int rv; 
 
    rv = printf("%d F is water's boiling point.\n", bph2o); 
    printf("The printf() function printed %d characters.\n", 
             rv); 
    return 0; 
}    

The code above generates the following result.