Menu Close

printf( ) function in C Program

Posted in C Program Exercises

1. printf( ) function

In C programming, printf() is one of the main output function. The function sends formatted output to the screen. The “f” in printf stands for “format” which indicates that it can be used to customize the formatting of the output text.

printf("Hello World");

The above command will output the text “Hello World” on the screen.

The printf() function does not automatically add a newline character at the end of the output. After the execution, the cursor remains at the end of the output without automatically moving to the next line. To move the cursor to the beginning of the next line, you can add a newline character “\n” at the end of the output text.

“\n” is an escape sequence

printf("Hello World\n");

above code will move the cursor to the beginning of the next line.

If there are line breaks within the text, they are also achieved by inserting line break characters. The line break character in C is represented by the escape sequence \n. When the \n escape sequence is encountered in a string, it indicates that a new line should begin at that point. For example, the following code would output the string “Hello\nWorld” on two separate lines:

printf("Hello\nWorld\n");

results:

The above example first outputs “Hello” and then adds a newline. On the next line, it outputs “World” at the beginning, followed by another newline.

The above example can also be written using two printf() statements, with the same result.

printf("Hello\n");
printf("World\n");

The printf() function is defined in the standard library header file stdio.h. Before using this function in a source code file, it is necessary to include this header file at the beginning of the file using the #include <stdio.h> directive.

2. A Placeholder in C Program

Detail: A placeholder 

Common formatting output functions include printf() and sprintf().

The placeholder starts with a percent sign (%) followed by a character that represents the type and format of the data to be output. For example, %d represents an integer, %f represents a floating-point number, %s represents a string, and so on.

Here are some common placeholders and their meanings:

  • %d: output integer
  • %i: output a integer
  • %f: output floating-point number
  • %c: output character
  • %s: output string
  • %p: output pointer address
  • %e: output floating-point number in scientific notation
  • %x: output hexadecimal integer

In addition to representing data types, placeholders can also be used to control output format, such as controlling output width, precision, alignment, and so on. These control characters can be combined with placeholders, such as %5d to output an integer with a width of 5.

Here’s a list of commonly used C data types and their format specifiers.

Data Type Format Specifier
int %d
char %c
float %f
double %lf
short int %hd
unsigned int %u
long int %li
long long int %lli
unsigned long int %lu
unsigned long long int %llu
signed char %c
unsigned char %c
long double %Lf

Example 2.1:

An Example of a Placeholder to Print An Integer

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("I am %i years old\n", 16);
    return 0;
}

In the example above, “I am %i years old\n” is the output text and “%i” is the placeholder, indicating that this position should be replaced with another value. The first character of the placeholder is always the percentage sign “%”, and the second character represents the type of the placeholder. “%i” means that the value inserted here must be an integer.

The second argument of printf() is the value that replaces the placeholder. In the example above, the integer 16 is used to replace “%i”. The output after execution is “I am 16 years old”.

Results:

In addition to the “%i” placeholder for integers, the “%s” placeholder is commonly used in C programming to indicate that a string value should be inserted.

Example 2.2:

An Example of a Placeholder to Print String

Here’s an example of using the “%s” placeholder:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("I am %i(%s) years old\n", 16, "sixteen");
    return 0;
}

 

In the example above, “%s” represents a string placeholder, which means the second argument of printf() must be a string value. In this example, the second argument is “Sixteen”. After execution, the output will be “I am sixteen years old”.

In outputting text, multiple placeholders can be used.

Example 2.3:

An Example of a Placeholder to Print String and Integer

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("I am %i(%s) years old\n", 16, "sixteen");
    return 0;
}


In the example above, the output text “I am %i(%s) years old” has two placeholders. The first one is a string placeholder “%i”, and the second one is an integer placeholder “%s”. They correspond to the second parameter (“16”) and the third parameter (“sixteen”) of the printf() function, respectively. After the execution, the output will be “I am 16(sixteen) years old”.

The parameters of printf() function correspond to the placeholders one-to-one. If there are n placeholders, the printf() function should have n+1 parameters. If the number of parameters is less than the number of placeholders, printf() may output arbitrary values from the memory.

The printf() function has many types of placeholders that correspond to the data types in the C language. Below, we list commonly used placeholders in alphabetical order for easy reference. Their specific meanings are explained in later sections.

The printf() function has many types of placeholders that correspond to the data types in the C language. Below, we list commonly used placeholders in alphabetical order for easy reference.

Their specific meanings are explained in later sections.

%a: Floating-point number.
%A: Floating-point number.
%c: Character. (char)
%d: Decimal integer.
%e: Scientific notation with lowercase e.
%E: Scientific notation with uppercase E.
%i: Integer, essentially equivalent to %d.
%f: Decimal number (including float and double types).
%g: Floating-point number with 6 significant digits. If the integer part exceeds 6 digits, it will automatically be converted to scientific notation, with the lowercase letter “e” representing the exponent.
%G: Equivalent to %g, except that the uppercase letter “E” represents the exponent.
%hd: Decimal short int type.
%ho: Octal short int type.
%hx: Hexadecimal short int type.
%hu: Unsigned short int type.
%ld: Decimal long int type.
%lo: Octal long int type.
%lx: Hexadecimal long int type.
%lu: Unsigned long int type.
%lld: Decimal long long int type.
%llo: Octal long long int type.
%llx: Hexadecimal long long int type.
%llu: Unsigned long long int type.
%Le: Scientific notation with long double type floating-point numbers.
%Lf: Long double type floating-point number.
%n: Number of characters printed so far. The placeholder itself does not print anything, it only stores the value in the specified variable.
%o: Octal integer.
%p: Pointer.
%s: String.
%u: Unsigned integer (unsigned int).
%x: Hexadecimal integer.
%zd: size_t type.
%%: Output a percent sign.

3. Output Format

Printf() syntax

printf("format string", argument1, argument2, ...);
  • The format string is a string that contains two types of objects: ordinary characters and format specifiers.
  • Ordinary characters (e.g. letters, digits, punctuation marks) are copied to the output stream.
  • Format specifiers begin with a percent sign (%) and are followed by one or more format characters. They specify the type of data to be printed and how it should be formatted.
  • Arguments are the values to be printed using the format specifiers in the format string.

With printf(), you can customize the output format of placeholders.

3.1 Limit the Output Widths

example 3.1  Printf() allows you to specify a minimum width for the placeholders right-aligned.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("%8d\n", 4567); // output "    4567"
    return 0;
}


The example above shows that “%8d” indicates that the minimum width of this placeholder is 8 digits. If the value is less than 8 digits, white-spaces will be added in front of it.

The output value is right-aligned by default, which means there are spaces in front of the output content. Adding a “-” after the “%” in the placeholder format will left-align the output value. For example, %-8d would left-align the integer value with a minimum width of 8 characters, adding spaces after the value if necessary.

Example 3.2 Printf() allows you to specify a minimum width for the placeholders, left-aligned.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("%-8dhere\n", 4567); 
    return 0;
}

 

The example above adds four spaces after the output “4567”. The purpose of adding “Here” is to see the number of spaces clearly.

Example 3.3 For decimals, A Placeholder limits the minimum display width for all numbers.

 

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("here|%12f\n", 567.89);
    return 0;
}

 

in the above example, %12f means that the floating-point number to be printed should take up at least 12 characters. Since the default display precision for a floating-point number is 6 digits after the decimal point, the resulting output will have 2 spaces added to the beginning to ensure that the total width is at least 12 characters.

3.2 Always Display the Positive and Negative Sign

By default, printf() does not display a + sign for positive numbers, only for negative numbers. To display a + sign for positive numbers as well, you can add a + sign after the % in the format specifier.

Example 3.2.1 Always Display the Positive and Negative Sign

<pre class="EnlighterJSRAW" data-enlighter-language="c">#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("%+d\n", 89); 
    printf("%+d\n", -89); 
    return 0;
}</pre>

In the example above, %+d ensures that the output number always has a sign.

3.3. Limiting the Number of Decimal Places

The precision of the floating-point number can be specified using a dot (.) followed by a number after the percentage symbol (%). The number following the dot represents the number of digits to be displayed after the decimal point. For example, %.2f means to display 2 digits after the decimal point.

Example 3.3.1 – Limiting the Number of Decimal Places

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Number is %.3f\n", 0.5);
    return 0;
}

In the example given, the placeholder %.3f is used to display the floating-point number with a precision of 3 decimal places after the decimal point.

this syntax can be combined with width limiters.

Example 3.3.2 – Limiting the Number of Decimal Places and Width Limiters

#include <stdio.h>
#include <stdlib.h>

int main()
{
   printf("Here|%7.3f\n", 0.5);
}

In the example above, “%7.3f” represents a minimum width of 7 characters and 3 decimal places when printing the floating-point number. Therefore, there are two spaces at the beginning of the printed string to fill up the minimum width of 7 characters.

Asterisk (*)

The  width limiters and decimal places can both be replaced with an asterisk (*) through arguments passed into the printf() function.

Example 3.3.3 an asterisk (*) through arguments passed into the printf() function

#include <stdio.h>
#include <stdlib.h>

int main()
{
   printf("%*.*f\n", 7, 3, 0.5);

   // equals to
   printf("%7.3f\n", 0.5);
}

In the above example, the two asterisks in %*.*f are passed into printf() as the two arguments 7 and 3.

3.4. Output Strings

The %s placeholder is used to output a string, and by default, it outputs the entire string. If you only want to output the beginning part of the string, you can use %.[m]s to specify the length of the output, where [m] represents a number that indicates the length to be outputted.

Example 3.4.1  Output part of a string

#include <stdio.h>
#include <stdlib.h>

int main()
{
   // Output My Dea
   printf("%.6s\n", "My Dear Friend!");
}

 

Leave a Reply