Wednesday, March 4, 2009

C# - Chapt 2: Literals, Variables and Data Types

2. Literals, Variables and Data Types

C# is a strongly typed language. That is:
1. Every variable has a data type.
2. Every expression also has a data type.
3. All assignments are checked for type compatibility.
4. There is no automatic correction or conversion of conflicting data types.
5. The C# compiler checks all the expressions and parameters to ensure that the types are compatible.



Important Definitions:
1. Class: A C# program is a collection of classes. A class is a set of declaration statements and methods. A method has executable statements.
2. Token: The smallest textual element that cannot be reduced further is called a token. There are 5 types of tokens in C#. These are:
i) Keywords
ii) Identifiers
iii) Literals
iv) Operators
v) Punctuation symbols
White spaces (space, tab and newline are spaces) and comments are not treated as tokens.
3. Keywords: Keywords are reserved words that have a specific meaning in a programming language. These keywords cannot be used as identifiers or variables. C# permits keywords to be used as identifiers provided the keyword is preceded by the @ symbol. However, this must be avoided.
4. Identifiers: Identifiers are created by the programmer and are used to give names to classes, methods, variables, namespaces, etc.
5. Literals: Literals are constant assigned to variables. Examples of literals are: 250, ‘A’, “Mumbai”.
6. Operators: Operators are symbols used in expressions. An operator acts on operands. Some operators like ‘+’ and ‘*’ require two operands (e.g. 23 + 67), but some operators are unary operators because they require only one operand (e.g., the unary minus operator, -23).
7. Punctuation Symbols: Symbols such as brackets, semicolon, colon, comma, period, etc are called punctuation symbols or punctuators or separators. They are used for grouping statements together, or for terminating a statement, etc.
8. Statements: A statement is an executable combination of tokens. A statement in C# ends with the semicolon symbol (;). Various types of statements in C# are:
i) Declaration statements ii) Expression statements iii) Selection statements
iv) Jump statements v) Interaction statements vi) labeled statements

vii) Empty statements

Keywords :

C# has 76 keywords. A few commonly used keywords are listed below:

bool
byte
char
decimal
double
float
int
long
sbyte
short
string
ulong
ushort
break const
case false
catch in
class new
continue null
do object
else private
for public
foreach return
goto struct
if true
switch void
try while


Literals:

Literals are value constants assigned to variables. The various types of literals in C# are as follows:
1. Numeric Literals
a. Integer Literals -- e.g., 250, 200, -187, 0, 0xcab (hexadecimal literal)
b. Real Literals -- e.g., 3.142, -96.4, 0.0074, 6.023E+3
2. Boolean Literals -- e.g., true, false
3. Character Literals
a. Single character literals -- e.g., ‘A’, ‘4’ , ‘?’, ‘ ‘
b. String literals -- e.g., “Welcome 2009”, “Hello”, “9869012345”
c. Backslash Character Literals -- These are the escape sequences. They are used for formatting the printed output. The most commonly used escape sequences are:
i. ‘\n’ -- new line character
ii. ‘\b’ -- back space
iii. ‘\f’ -- form feed
iv. ’\t’ -- horizontal tab
v. ’\v’ -- vertical tab


Variables:

1. A variable is a named data storage location.
2. A variable is an identifier created by the programmer.
3. A variable refers to some storage location in the computer’s memory.
4. The value of a variable can change during the execution of a program.
5. Every variable has a data type. E.g., an int variable can only store integer type data, etc.
6. The place at which a variable is declared determines the scope of that variable in the program.
7. All variable must be declared before they are used in a program.
8. The data type of a variable determines the following:
a. The space occupied in the memory by the variable. E.g., in C#, int occupies 4 bytes.
b. The operations that can be carried out on that variable. E.g., we can carry out the operation of % (modulus) on integer operands but not on char operands.
c. The range of values that can be stored in the variable.

Rules for forming variable names:
1. The variable name should be meaningful.
2. The first character must be a letter.
3. Remaining characters can be letters, digits or underscore (_).
4. C# is case-sensitive. That is, the variable MARKS and marks are different.
5. C# keywords cannot be used as variable names.

Here are some examples of valid and invalid variable names. For each keyword, write “Valid” or “Invalid”. If it is invalid, justify.

Variable Name Valid/Invalid Reason if invalid
marks
mks in java
for
balance
$balance
2papers
tax_paid


Data Types:

C# supports two types of data types. These are:
1. Value types, and
2. Reference Types.

1. Value types :-
i) These are of fixed length.
ii) They are stored on a stack.
iii) When a variable is assigned to another variable, the values are actually copied.
There are two categories of value types: predefined types (int, float, char, etc) and user-defined types (e.g., structure)

Predefined or Simple Types:
a) Boolean type
b) Character type
c) Numeric type
a. Integer type
i. Signed types
ii. Unsigned types
b. Floating point
c. Decimal types

2. Reference types :-
i) These are of variable length.
ii) They are stored on a heap.
iii) When an assignment occurs between reference variables, only the reference is copied. The actual value remains the same in memory. There are now two references to the same memory location.

Reference type variables are of two types:
a) User-defined / complex, e.g., classes, arrays, interfaces, delegates
b) Predefined / simple e.g., string type, object type.

The object type is the base type for all other inbuilt and user-defined types in C#. The string type is used for creating and performing many operations on string type data.

Default Values of Variables:
A variable may be explicitly assigned a value or it may be assigned a default value by the compiler. Following types of variables are automatically initialized to their default values in C#:
Array elements, Static variables, and Instance variables.

Data Type Default value
Integer 0
Char ‘\x000’
Float 0.0f
Double 0.0d
Decimal 0.0m
Boolean false


Constant Variables

Variables whose values do not change during the execution of the program are called constants.
E.g., suppose the programmer declares a variable called PI which should not change during the program execution. We declare this variable as follows:

const PI = 3.142;

Advantages of using constants are:
i) Programs are easier to read. It is easier to read an expression area = PI * r * r rather than the expression area = 3.142 * r * r.
ii) Programs are easier to modify. E.g., if we want to change the value of PI to 3.14.156, we have to do so in only one place, instead of throughout the program.
iii) Values of such constants cannot be changed even accidentally by the programmer as the compiler will give an error.

Note:
i) const must be declared at class level. They cannot be declared at method level.
ii) Once a constant has been assigned a value, it should not be assigned another value.
iii) In C#, constants are assigned for data types.


Scope of Variables:

C# is a block-structured language. The lifetime of a variable and its accessibility is known as the scope of the variable. A variable has a scope or visibility within a particular block. That is, the variable can be accessed within that block. The scope of the variable depends upon the place of declaration and type of variable.

Types of variables in C#:
• Static variables – declared at class level; also known as filed variables. Scope of this variable ends when the Main function ends.
• Instance variables - declared at class level; also known as filed variables. Scope of this variable ends when the Main function ends.
• Array variables – these come into existence when the array is created and exist only so long as the array exists.
• Local variables – variables declared inside a method. These variables are not available for use outside the method in which they are declared.
• Value parameters – exist till the end of the method
• Reference parameters – do not create new location but only refer to an existing location



Example 1: Consider the following code:

using System;

namespace localscope
{
class Scope
{
public static void Main()
{
for (int x = 1; x <= 10; x++)
{
Console.WriteLine("x is {0}", x);
}
Console.WriteLine("Outside the loop, x is {0}", x);
}

}
}

When this program is compiled, we get the following error:
“The name 'x' does not exist in the current context”

The variable x is declared as part of the “for” statement. As soon as the “for” statement is completed, the variable x goes out of scope. Since it is out of the scope, the second WriteLine statement generates an error.

IMPORTANT QUESTIONS

1. “C# is a strongly typed language”. Explain this statement.
2. Define the term “token” What are the types of tokens in C# ?
3. Distinguish between identifiers and keywords. Can a keyword be used as an identifier?
4. Define the term “separators”. Give examples of at least 5 separators in C#.
5. State the various types of literals used in C#. Give two examples of each type.
6. What are escape sequences? Give examples.
7. What is a variable? What is the effect of declaring a variable?
8. Is it necessary to declare a variable in C#? Give example of one programming language you have learnt in which variables need not be declared.
9. State the rules for forming valid variable names.
10. Explain the difference between value types and reference types in C#.
11. What is the benefit of declaring variables as constants in a C# program? State the rules that must be followed when declaring const variables.
12. Explain the term scope of a variable and for different types of variables, explain their scope.

No comments:

Post a Comment