The Basics of C Programming


The printf statement allows you to send output to standard out. For us, standard out is generally the screen (although you can redirect standard out into a text file or another command).

Here is another program that will help you learn more about printf:


#include <stdio.h>

int main()
    int a, b, c;
    a = 5;
    b = 7;
    c = a + b;
    printf("%d + %d = %d\n", a, b, c);
    return 0;

Type this program into a file and save it as add.c. Compile it with the line gcc add.c -o add and then run it by typing add (or ./add). You will see the line "5 + 7 = 12" as output.

Here is an explanation of the different lines in this program:

  • The line int a, b, c; declares three integer variables named a, b and c. Integer variables hold whole numbers.
  • The next line initializes the variable named a to the value 5.
  • The next line sets b to 7.
  • The next line adds a and b and "assigns" the result to c. The computer adds the value in a (5) to the value in b (7) to form the result 12, and then places that new value (12) into the variable c. The variable c is assigned the value 12. For this reason, the = in this line is called "the assignment operator."
  • The printf statement then prints the line "5 + 7 = 12." The %d placeholders in the printf statement act as placeholders for values. There are three %d placeholders, and at the end of the printf line there are the three variable names: a, b and c. C matches up the first %d with a and substitutes 5 there. It matches the second %d with b and substitutes 7. It matches the third %d with c and substitutes 12. Then it prints the completed line to the screen: 5 + 7 = 12. The +, the = and the spacing are a part of the format line and get embedded automatically between the %d operators as specified by the programmer.