Output of items in C

The functions used, putchar and printf are part of the library stdio.h and this must be included in to a program which wants to use it.

The function putchar

The simplest output function simply prints a single char value as its visible representation. This is int putchar(int c).

The function printf

We can perform all output using the function, int printf(const char*, ...). This is an abbreviation for print formatted and allows values to be printed in a format string. printf is defined as an int function, but we often write it as a procedure. It requires at least one parameter, which must be written as a string literal, enclosed in double quotes. This defines what will be printed.

In its simplest form printf simply prints out the format string unchanged, e.g.

      printf("Hello world\n");
The newline character forces the next printing to start on a new line. No output may appear until a newline is specified as being printed, so always use one if you want to make sure that what you are printing will be displayed immediately, for instance when adding print statements to help debug your programs.

Printing items

If we want to print the value of a number, we have to add a formatting description into the format string at the point where the value is to appear and add the value of the number to the list of parameters we pass to printf. Note that printf can take any number of parameters required to match these descriptors, unlike most functions where the number of parameters is fixed.
   printf("val1 = %d and val2 = %d\n", val1, val2);
In this example we want to print the values currently stored in the int variables val1 and val2.and then start a new line of output. The %d sequences are formatting descriptors requiring something in the form of a whole decimal number to be printed, embedded within the rest of the format string. In this case, there is a space between them and so they will appear separated by it. The string ends with the newline escape and so a new line is begun immediately after the second number.

As well as numbers being included in formatting strings, we can specify that individual characters stored in char variables or strings of characters, held within char arrays and terminated by the null character, should be included. The format descriptors for these are %c and %s respectively. Thus:

#include <stdio.h>
void main() {
   int i1 = 3; char c1 = 'e'; float f1 = 3.4;
   char s1[4];
   strcpy(c1,"yes");
   printf("int %d char %c float %f string %s\n", i1, c1, f1, s1);
}
will output the line
int 3 char e float 3.400000 string yes
Plain text to compile.

Exercises on this section.


Next - input in C.

Back to Input and Output.

Back to Contents page.