Variables and Assignments - Example

This section provides a tutorial example on how to use variables, variable declaration statements, and assignment statements.

Now let's review what have learned in this section with a sample program:

```// Variables.cs
// Copyright (c) 2015, HerongYang.com, All Rights Reserved.

class Variables {
public static void Main() {
bool is_ok;
int n;
int num_of_sec;
long number_of_sec_in_a_year;
float sqrt_s;
double sqrt_d;
char c1, c2, c3;
char cr, cn;

is_ok = true;
num_of_sec = 86400;
number_of_sec_in_a_year = 30458700;
sqrt_s = 1.4142F;
sqrt_d = 1.4142135623730950488016887242097;
c1 = 'a';
c2 = 'A';
c3 = '0';
cr = '\r';
cn = '\n';

n = 1;
System.Console.WriteLine("Value of is_ok = {0}.", is_ok);
System.Console.WriteLine("1 day = {0} seconds.", num_of_sec);
System.Console.WriteLine("1 year = {0} seconds.",
number_of_sec_in_a_year);
System.Console.WriteLine(
"Square root of 2 (float) = {0}.", sqrt_s);
System.Console.WriteLine(
"Square root of 2 (double) = {0}.", sqrt_d);
System.Console.WriteLine(
"Some regular characters: {0}, {1}, {2}.", c1, c2, c3);
System.Console.WriteLine("The return character: {0}.", cr);
System.Console.WriteLine("The new line character: {0}.", cn);
n = 9;
System.Console.WriteLine("WriteLine() is used {0} times.", n);
}
}
```

Output of the program will be:

```Value of is_ok = True.
1 day = 86400 seconds.
1 year = 30458700 seconds.
Square root of 2 (float) = 1.4142.
Square root of 2 (double) = 1.4142135623731.
Some regular characters: a, A, 0.
.he return character:
The new line character:
.
WriteLine() is used 9 times.
```

Observations from this program:

• Suffix 'F' is used in literal "1.4142", because real literals are considered to be of 64-bit size, which requires variable type "double" to hold the value. The suffix 'F' is forcing a real literal to be of 32-bit size.
• Literal "1.4142135623730950488016887242097" gets truncated and rounded to "1.4142135623731" during the execution of the assignment statement, because the double variable name sqrt_d can only hold about 14 decimal digits.
• Variable "n" gets assigned twice in the program. Variables can be assigned to new values many times.

Advice: Avoid using "int" and "float". Use "long" and "double" instead. In the old days, 32-bit data requires less memory to store and computer time to process than 64-bit data. This is not totally true now, because today's computers are designed to store and process data 64 bits at a time, not 32 bits at a time.

Last update: 2015.

Table of Contents