Initializing Numeric Variables
When any variable is declared, the compiler is instructed to set aside storage space for the variable. However, the value stored in that space, the value of the variable, is not defined. It might be zero, or it might be some random "garbage" value. Before using a variable, you should always initialize it to a known value. Let us take this example:
int count; /* Set aside storage space for count */
count = 0; /* Store 0 in count */
This statement uses the equal sign (=), which is C's assignment operator. You can also initialize a variable when it's 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 rate = 0.01, complexity = 28.5;
Be careful not to initialize a variable with a value outside the allowed range. Here are two examples of out-of-range initializations:
int amount = 100000;
unsigned int length = -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.
Let us take the following example to calculate the total number of sectors in a Disk:
// Model Program To Calculate Sectors in A Disk //
#include<stdio.h>
#define SECTOR_PER_SIDE 63
#define SIDE_PER_CYLINDER 254
void main()
{
int cylinder=0;
clrscr();
printf("Enter The No. of Cylinders in the Disk \n\n\t");
scanf("%d",&cylinder); // Get the value from the user //
printf("\n\n\t Total Number of Sectors in the disk = %ld", (long)SECTOR_PER_SIDE*SIDE_PER_CYLINDER* cylinder);
getch();
}
The output of the program is as follows:
Enter The No. of Cylinders in the Disk
1024
Total Number of Sectors in the disk = 16386048 |
In this example we see three new things to learn. #define is used to use symbolic constants in the program or in some cases to save time by defining long words in small symbols.
Here we have defined the number of sectors per side that is 63 as SECTOR_PER_SIDE to make the program easy to understand. The same case is true for #define SIDE_PER_CYLINDER 254. scanf() is used to get the input from the user.
Here we are taking the number of cylinders as input from the user. * is used to multiply two or more value as shown in the example.
getch() function basically gets a single character input from the keyboard. By typing getch(); here we stop the screen until any key is hit from the keyboard.
|