Jumat, 05 Maret 2010

Variables and Printf

Variables

As a programmer, you will frequently want your program to "remember" a value. For example, if your program requests a value from the user, or if it calculates a value, you will want to remember it somewhere so you can use it later. The way your program remembers things is by using variables. For example:

    int b;

This line says, "I want to create a space called b that is able to hold one integer value." A variable has a name (in this case, b) and a type (in this case, int, an integer). You can store a value in b by saying something like:

    b = 5;

You can use the value in b by saying something like:

    printf("%d", b);

In C, there are several standard types for variables:

  • int - integer (whole number) values
  • float - floating point values
  • char - single character values (such as "m" or "Z")

Printf

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 

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.
Source :here

Tidak ada komentar:

Posting Komentar