C Printf: Print What You Want, the Way You Want It!

c printfC is one of the oldest and most popular programming languages. It’s highly structured, and yet flexible nature, makes it widely used especially in embedded system programming. In this article, we will explore a simple yet a powerful function of C language known as printf.

We assume you have a basic exposure to C. If not, don’t fret, C is an easy language to learn. You can take this basic C course for beginners to start off.

About Printf()

With any program, you’ll most likely want to display something on screen – either a question, a statement, or perhaps showing the result. How would you do that?  C’s printf statement gives you a structured way to do that, with a wide range of reliable formatting options. printf() is a default library function in C and is bundled as part of the STDIO (standard Input Output) library. This function is declared and the concerned macros are defined in the header file “stdio.h”. It can be used to print “integer, string, float, octal, decimal and character” onto your screen. Note that this function is that it is case sensitive ie printf() is different from Printf(). The syntax for printf() is

printf("format specifier", value);

All the parameters within the printf() should be in lower case only.

We’ll walk you a couple of examples to help you understand how to use function printf in C programming, to get the results you want. For learning purposes, we suggest that it’s better to actually type the code and try out these examples for yourself instead of just reading through it. At any time, if you want to get deeper with C, feel free to check out this excellent course on C programming.

Example 1: How to Print “Hello World”

#include<stdio.h>
int main()
{
   printf(“Hello World\n”); 
   return 0; 
}

Programmers just love to start with this example, and so that’s where we start as well! Save this program under the file name helloworld.c and compile this program. When you run it, the output should be “Hello World”. Now let’s take a look at each component of this program.

  • Stdio.h- is the  Standard Input/Output library header file. This file has the commands for reading from the keyboard and printing the processed commands on the screen.
  •  int main() – The value returned would be an integer  and “int” is the short form for integer. Every C program starts with a main().
  • {} – The curly brackets. These brackets are used to group together the commands in C language. It marks the beginning and end of a group of commands or functions.
  • printf(“Hello World\n”);  The printf is the functionused for printing things on the screen. In this example it’s “Hello World”. The words “Hello World” are placed between the inverted commas because they are strings. The strings must be always written between the inverted commas. The ‘\n’ is called an escape sequence. Here it represents a newline.
  • return 0 – We declared that the main() must return an integer value. Here with the return 0; we are returning the value null to the OS. This command tells the operating system there are no errors while running the program.

Printf() Format Options

Options the printf() should take are defined in the ANSI standard. You’ll have to ensure that the compiler you are using conforms to ANSI standard, in order for it to all work as expected.

Format specifiers define how the values will be returned by the program – that is whether value is an integer, decimal or string. Take a look at the table below

%i or %d

Int

%c

Char

%f

Float (it displays the decimal points.)

%s

String

 

Let’s understand this better with another example to see how the formatted output for printf looks:

#include<stdio.h>
        main()
        {
        int a,b;
        float c,d;
                    a = 17;
                    b = a / 2;
                    printf("%d\n",b);
                    printf("%3d\n",b);
                    printf("%03d\n",b);
                    c = 15.3;
                    d = c / 3;
                    printf("%3.2f\n",d);
        }

The output for the above program would be

8
  8
008
5.10

Here’s what it means

1.      The first printf statement returns the decimal value 8 since we specified the format as %d

2.      In the second printf statement, we print the same decimal value with three spaces(%3d) to the right.

3.      The third printf statement output has a width of three digits, where the space is replaced with two zeros.

4.      The fourth printf statement returns three positions before the decimal point and 2 digits after the decimal point.

Commonly Used Escape Sequence

To print things like a tab, a newline or a backspace, you need some special characters. The character combinations for these are known as escape sequences. An escape sequence starts with a backslash (\) followed by a character. Since backslash is used for escape sequences, if you want to print a backslash, type two backslashes (\\). So the program will invoke the first backslash to initiate the escape sequence and second will print the backslash. Here are the commonly used escape sequences.

  • \n (newline)
  • \t (tab)
  • \v (vertical tab)
  • \f (new page)
  • \b (backspace)
  • \r (carriage return)

Combining Strings and Integers  Using Printf

In the previous examples we used integers and floats. Here lets see how you can print a string (that’s what normal text is called in C!) on your screen using printf().

#include<stdio.h>
main()
{
        printf("The color of the sky: %s\n", "blue");
        printf("First number is : %d\n", 54321);
        printf("Second number: %04d\n", 52);
        printf("Third number: %i\n", 4231);
        printf("Float number: %3.2f\n", 3.14159);
        printf("Hexadecimal: %x\n", 255);
        printf("Octal: %o\n", 255);
        printf("Unsigned value: %u\n", 150);
        printf("Just print the percentage sign %%\n", 10);
}

The output of the example would be:

1.   The color of the sky: blue
2.   First number: 54321
3.   Second number: 0052
4.   Third number: 4231
5.   Float number: 3.14
6.   Hexadecimal: ff
7.   Octal: 377
8.   Unsigned value: 150
9.   Just print the percentage sign %

Here’s what it means, and how we got here:

  • The output of the sixth printf statement in the example is Hexadecimal:ff. The hexadecimal notation begins from 0 to 9 and A through F, where A is 10 and F is 15.
  • In the last printf statement, only the percentage sign is printed and not the number 10. Have you wondered why? If you want to print a percentage number, your printf statement should be written like this: printf(“%2d%%\n”, 10); .

Formatting Strings in Printf()

In the examples so far, we’ve looked at how to format the numbers, and special characters. But sometimes you may want to format the strings ie the text as well. Let’s check out some ways to do that.

#include<stdio.h>
main()
{
        printf(":%15s:\n", "Hello, world!");
        printf(":%.10s:\n", "Hello, world!");
}

The output of these printf statements would be

:  Hello, world!:

:Hello, wor:

Here, the first printf statement prints 15 characters, and the second printf statement prints only 10 characters of the string.

Of course, this is just the tip of the iceberg. There are many more printf formatting options for you to experiment with. You should try experimenting with them. And if you’d like to spice it up a bit, try out this course to learn C the hard way! Intrigued? Go check it out. It’s not really that hard!