Monday, July 2, 2012

CPro1 Lecture: Numeric variables and Constants

▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
Numeric Variables and Constants
OBJECTIVE
Computer programs usually work with different types of data and need a way to store the values being used.  These values can be numbers or characters.  C has two ways of storing number values - variables and constants - with many options for each.  A variable is a data storage location that has a values which can change during program execution.  In contrast, a constant has a fixed value that cannot change.  This chapter teaches you
·  How to create variable names in C.
·  The use of different types of numeric variables.
·  The differences and similarities between character and numeric values.
·  How to declare and initialize numeric variables.
·  C’s two types of numeric constants.

Computer programs usually work with different types of data and need a way to store the values being used.  These values can be numbers or characters.  C has two ways of storing numbers -- variables and constants -- with many options for each.  A variable is a data storage location that has a value which can change during program execution.  In contrast, a constant has a fixed value that cannot change.
Computer Memory
A computer uses random-access memory (RAM) to store information while it is operating.  RAM is located in integrated circuits, or chips, inside your computer.  RAM is volatile, which means it’s erased and replaced with new information as often as needed.  Being volatile also means that RAM “remembers” only while the computer is turned on and loses its information when you turn off the computer.
Each computer has a certain amount of RAM installed.  The amount of RAM in a system is usually specified in kilobytes (K), such as 256K, 512K, or 640K.  One kilobyte of memory consists of 1024 bytes.  Thus, a system with 256K of memory actually has 256 times 1024, or 262,144, bytes of RAM.  RAM is also referred to in megabytes.  One megabyte is 1024 kilobytes.
A byte is the fundamental unit of computer data storage.  The RAM in your computer is organized sequentially, one byte following another.  Each byte of memory has a unique address by which it is identified, an address that also distinguishes it from all other bytes in memory.  Addresses are assigned to memory locations in order, starting at 0 and increasing to the system limit.
Variables
A variable is a named data storage location in your computer’s memory.  By using a variable’s name in your program, you are, in effect, referring to the data stored there.
Variable Names
In C, variable names must adhere to the following rules
*   The name can contain letters, digits, and the underscore character (_).
*   The first character of the name must be a letter.  The underscore is also a legal first character, but its use is not advised.
*   Case matters (that is, upper- and lowercase letters).  Thus, the names count and Count refer to two different variables.
*   C keywords cannot be used as variable names.  A keyword is a word that is part of the C language.  (See Appendix B for a complete list of all C keywords).
*   C variable name can be up to 31 characters long.  (It can actually be longer than that, but the compiler looks only at the first 31 characters of the name.)
Many naming conventions are used for variable names created from multiple words.  One is by using an underscore to separate words in a variable name.  For example: interest_rate.  The second style is called camel notation.  Instead of using spaces, the first letter of each word is capitalized.  Instead of interest_rate, the variable would be named InterestRate.  Camel notation is gaining popularity because it is easier to type a capital letter than an underscore.
DO / DON’T
DO       use variable names that are descriptive.
DO       adopt and stick with a style for naming your variables.
DON’T  start your variable names with an underscore unnecessarily.
DON’T  name your variables with all capitals unnecessarily.



Numeric Variable Types
C’s numeric variables fall into the following two main categories:
·         Integer Variables hold values that have no fractional part (that is, whole numbers only).  Integer variables come in two flavors:  signed integer variables can hold positive or negative values, whereas unsigned integer variables can hold only positive values (and 0, of course).
·         Floating-point variables hold values that have a fractional part (that is, real numbers).
Table 3.1. C’s numeric data types.
                                                                                          Bytes                           
Variable type                            Keyword                       required           Range
character                                               char                      1                      -128 to 127
integer                                      int                       2                      -32768 to 32767
short integer                              short                     2                      -32768 to 32767
long integer                               long                      4                      -2,147,483,648 to 2,147,438,647
unsigned character                    unsigned char 1                      0 to 255
unsigned integer                                    unsigned int              2                      0 to 65535
unsigned short integer               unsigned short       2                      0 to 65535
unsigned long integer                unsigned long 2                      0 to 4,294,967,295
single-precision floating-point    float                     4                      1.2E-38 to 3.4E38 *
double-precision floating-point   double                    8                      2.2E-308 to 1.8E308**

*  Approximate range; precision = 7 digits
** Approximate range; precision = 19 digits
Approximate range means the highest and lowest values a given variable can hold.
Precision means the accuracy with which the variable is stored. (For example, if you evaluate 1/3, the answer is 0.33333...... with 3s going to infinity.  A variable with a precision of 7 stores seven 3s.)
On different machines, different variable types may have a different size on different sizes.  C does make some guarantees, thanks to the ANSI Standard.  There are five things that can be counted on:
·         The size of a char is 1 byte.
·         The size of a short is less than or equal to the size of an int.
·         The size of an int is less than or equal to the size of a long.
·         The size of an unsigned is equal to the size of an int.
·         The size of a float is less than or equal to the size of a double.
Variable Declarations
Before you can use a variable in a C program, it must be declared.  A variable declaration informs the compiler of the name and type of a variable and optionally initializes the variable to a specified value.  If your program attempts to use a variable that has not been declared, the compiler generates an error message.  A variable declaration has the following form:
typename varname;
where:     typename specifies the variable type and must be one of the keywords given in Table 3.1
               varname  is the variable name, which must follow the rules in naming variables.
example: int count, number, start;  /* three integer variable */
         float percent, total;             /* two float variables */

The  typedef  Keyword
The typedef keyword is used to create a new name for an existing data type.  In effect,  typedef creates a synonym.  For example, the statement
typedef int integer;
creates integer as a synonym for int.  You can then use integer to define variables of type int.
integer count;
Initializing Numeric Variables
When you declare a variable, you instruct the compiler to set aside storage space for the variable.  However, the value stored in that space -- the value of the variable -- is not defined.  It may be zero, or it may be some random “garbage” value.  Before using a variable, you should always initialize it to a known value.  This can be done independent of the variable declaration by using an assignment statement.
int count;     /* set aside storage space for count */
count = 0;     /* initialize count to 0 */
You can also initialize a variable when it is declared.  To do so, follow the variable name in the declaration statement with an equal sign and the desired initial value.
int count = 0;
double percent = 0.01, taxrate = 28.5;
Be careful not to initialize a variable with a value outside the allowed range.  Here are some examples of out-of-range initializations:
int weight = 100000; 
unsigned int value = -2500;
The C compiler does not catch such errors.  Your program may compile and link, but you may get unexpected results when the program is run.
DO / DON’T
DO       understand the number of bytes that variable types take for your computer
DO       use typedef to make your programs more readable.
DO       initialize variables when you declare them whenever possible.
DON’T  use a variable that has not been initialized.  Results can be unpredictable!
DON’T use a float or double variable if you are only storing integers.  Although they will work, using them is inefficient.
DON’T  try to put numbers into variable types that are too small to hold them!
DON’T  put negative numbers into variables with an unsigned type.

Constants
Like a variable, a constant is a data storage location used by your program.  Unlike a variable, the value stored in a constant cannot be changed during execution.  C has two types of constants, each with its own specific uses.
Literal Constants
A literal constant is a value that is typed directly into the source code wherever it is needed.  Here are two examples:
int count = 20;     
float tax_rate = 0.28;
The 20 and 0.28 are literal constants.
A literal constant written with a decimal point is a floating-point constant and is represented by the C compiler as a double-precision number.  Floating-point constants can be written in standard decimal notation, as shown in these examples:
123.456      
0.019
100.
Floating-point constants can also be written in scientific notation.  Scientific notation is particularly useful for representing extremely large and extremely small values.  In C, scientific notation is written as a decimal number followed immediately by an E or e and the exponent.  For example:
1.23E2                  123 times 10 to the 2nd power, or 123
4.08e6                  4.08 times 10 to the 6th power, or 4,080,000
0.85e-4                 0.85 times 10 to the -4 power, or 0.000085
A constant written without a decimal point is represented by the compiler as an integer number.  Integer constants can be written in three different notations:
*       A constant starting with any digit other than 0 is interpreted as decimal integer.
*       A constant starting with the digit 0 is interpreted as an octal integer.
*       A constant starting with 0x or 0X is interpreted as a hexadecimal constant.
Symbolic Constants
A symbolic constant is a constant that is represented by a name (symbol) in your program.  Like a literal constant, a symbolic constant cannot change.  Whenever you need the constant’s value in your program, you use its name as you would use a variable name.  The actual value of the constant needs to be entered only once, when it is first defined.
C has two methods for defining a symbolic constant, the #define directive and the const keyword.  The #define directive is used as follows:
#define CONSTNAME literal
Example:
#define  PI  3.14159
Note that #define lines do not end with a semicolon (;).  #defines can be placed anywhere in your source code, but most commonly, programmers group all #defines together, near the beginning of the file and before the start of the main().
The second way to define a symbolic constant is with the const keyword. const is a modifier that can be applied to any variable declaration.  A variable declared to be const can’t be modified during program execution -- only initialized at the time of declaration.  Here are some examples:
const int count = 100;
const float pi = 3.14159;
const long debt = 12000000, float tax_rate = 0.21;
Note that  if your program tries to modify a const variable, the compiler generates an error message.  For example,
const int count = 100;
count = 200; /* Does not compile! Cannot reassign or alter the value of a constant */
DO / DON’T
DO       use constants to make your programs easier to read.
DON’T  try to assign a value to constant after it has already been initialized.

No comments:

Post a Comment