Wednesday, February 25, 2009

Assigning values to variables

You can assign values to variables via compile-time initialization and run time initialization. In both ways, to assign a value to a variable, or let a variable have a initial value, we use the assigning operator =.
  • compile-time initialization
Compile time initialization is the process of assigning, or initializing values to variables while declaring the variables.
Example:

int NumStudents = 5;
double Price = 21.8;
char letter = 'A';
  • run-time initialization
Run time initialization is the process of assigning or initializing values to variables after you have declared the variables.
Example:

int NumStudents;
double Price;
char letter;

NumStudents = 5;
Price = 21.8;
letter = 'A';
If you have more than 1 variable of the same data type, you can rewrite your code to make it neater. Example:

int NumStudents = 5;
int NumTeachers = 10;
int NumAdmins = 3;

We can rewrite it to:

int NumStudents = 5, NumTeachers = 10, NumAdmins = 3;

We can declare int on 1 line rather than each variable, since NumTeachers and NumAdmins share the same data type with NumStudents, which is int.

No comments: