WHAT ABOUT VARIABLES
C provides the programmer with FOUR basic data
types. User defined variables must be declared before they
can be used in a program.
Get into the habit of declaring variables using lowercase characters. Remember that C is case sensitive, so even though the two variables listed below have the same name, they are considered different variables in C.
sum Sum
The declaration of variables is done after the opening brace of main(),
#include <stdio.h> main() { int sum; sum = 500 + 15; printf("The sum of 500 and 15 is %d\n", sum); } Sample Program Output The sum of 500 and 15 is 515
It is possible to declare variables elsewhere in a program, but lets start simply and then get into variations later on.
The basic format for declaring variables is
data_type var, var, ... ;
where data_type is one of the four basic types, an integer, character, float, or double type.
The program declares the variable sum to be of type INTEGER (int). The variable sum is then assigned the value of 500 + 15 by using the assignment operator, the = sign.
sum = 500 + 15;
Now lets look more closely at the printf() statement. It has two arguments, separated by a comma. Lets look at the first argument,
"The sum of 500 and 15 is %d\n"
The % sign is a special character in C. It is used to display the value of variables. When the program is executed, C starts printing the text until it finds a % character. If it finds one, it looks up for the next argument (in this case sum), displays its value, then continues on.
The d character that follows the % indicates that a decimal integer is expected. So, when the %d sign is reached, the next argument to the printf() routine is looked up (in this case the variable sum, which is 515), and displayed. The \n is then executed which prints the newline character.
The output of the program is thus,
The sum of 500 and 15 is 515 _
Some of the formatters for printf are,
Cursor Control Formatters \n newline \t tab \r carriage return \f form feed \v vertical tab Variable Formatters %d decimal integer %c character %s string or character array %f float %e double
The following program prints out two integer values separated by a TAB It does this by using the \t cursor control formatter #include <stdio.h> main() { int sum, value; sum = 10; value = 15; printf("%d\t%d\n", sum, value); } Program output looks like 10 15 _
©Copyright B Brown. 1984-1999. All rights reserved.