Sunday, May 5, 2013

Printf working

printf()  Working

#include<stdio.h>
#include<conio.h>
void main()
{
    int a, b, c;
    a = 10;
    b = 10;
    c = a + b;
    printf("%d + %d = %d\n", a, b, c);
    getch();
}


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 10.
  • The next line sets b to 10.
  • The next line adds a and b and "assigns" the result to c. The computer adds the value in a (10) to the value in b (10) to form the result 20, and then places that new value (20) into the variable c. The variable c is assigned the value 20. For this reason, the = in this line is called "the assignment operator."
  • The printf statement then prints the line "10 + 10 = 20." 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 10 there. It matches the second %d with b and substitutes 10. It matches the third %d with c and substitutes 20. Then it prints the completed line to the screen: 10 + 10 = 20. 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.

No comments:

Post a Comment