Literals, Variables and Data Types.pptx

60
Literals, Variables and Data Types A programming language is designed to manipulate certain kinds of data consisting of numbers, characters and strings provides useful output known as information to the user. The smallest non-reducible, textual elements in a program are referred as tokens.

Transcript of Literals, Variables and Data Types.pptx

Literals, Variables and Data Types

A programming language is designed to manipulate certain kinds of data consisting of numbers, characters and strings provides useful output known as information to the user.

The smallest non-reducible, textual elements in a program are referred as tokens.

Literals, Variables and Data TypesC# program is collection of tokens, comments and whitespaces. C# includes the following five types of tokens.

• Keywords• Identifiers• Literals• Operators and Punctuators.

Whitespaces and comments are not tokens though they act as separators for tokens.

Literals, Variables and Data Types

C# keywords

Literals, Variables and Data TypesKeywords are essential part of language definition. They implement specific features of the language.

Identifiers are program designed tokens. They are used for naming classes, methods, labels, namespaces, interfaces etc.

C# identifiers enforce the following rulesa. They can have alphabets, digits and underscore

characters.b. They must not begin with digit.c. Upper case and lower case characters are distinct.d. Keywords in a stand-alone mode cannot be used as

identifiers.

Literals, Variables and Data TypesC# permits the use of keywords as identifiers when they are prefixed with ‘@’ character.

Literals are the way in which the values that are stored in variables are represented.

Operators are symbols used in expressions to describe operations involving one or more operands.

Punctuators are symbols used for grouping and separating code. They define shape and function of a program.

Literals, Variables and Data Types

Punctuators are also known as separators which include:() {} : [] ; , .

Statements are like sentences in natural languages. A statement is an executable combination of tokens ending with semicolon. C# implements several type of statements. They include

Literals, Variables and Data Types Empty Statements Labeled Statements Declaration Statements Expression Statements Selection Statements Interaction Statements Jump Statements Try Statements The Checked Statements The unchecked Statements The lock Statements The using Statements

Literals, Variables and Data TypesIdentifier example

Literals, Variables and Data Types

LiteralsLiterals are value constants assigned

to variables (or results of expressions).C# supports several types of literals as shown in fig.

Literals, Variables and Data TypesInteger Literals

An integer literal refers to sequence of digits. There are two types integers namely decimal integers and hexadecimal integers.

Decimal integers consists of digits 0 through 9 preceded by optional minus sign.

Ex: 123 -651 0 654321

Embedded spaces, commas and non-digit characters are not permitted between digits.

Ex. 15 75020,000 and $2000

Literals, Variables and Data TypesA sequence of digits preceded by 0x or 0X is considered as hexadecimal integers. It may also include alphabets A through F or ‘a through f’

Following are the examples of valid hex integers.

0X2 0X9F 0Xbcd 0x

Literals, Variables and Data TypesReal Literals

Integer literals are inadequate to represent quantities that vary continuously such as distances, heights, temperatures, prices and so on.

These quantities are represented by numbers containing fractional parts like 17.548 Such numbers are called real(or floating point) numbers. The examples are 0.083, -0.75 etc

Literals, Variables and Data TypesA real literal may also be expressed in exponential (or scientific) notation. For example the value 215.65 can be written as 2.1565e2 in exponential notation.

The general form is mantissa e exponent, The mantissa is either real number expressed in decimal notation or an integer. The exponent is an integer with optional plus or minus sign.

Literals, Variables and Data TypesBoolean LiteralsThere are two Boolean literal values:a. True b. FalseThey are used as values for relational expressions.

Single Character LiteralsA single character literal or simply character constant contains a single character encoded within a pair of single quotes. For ex: ‘a’, ‘X’ etc

Literals, Variables and Data TypesString Literal It is a sequence of characters enclosed between double quotes. The characters may be alphabets, digits and special characters.Ex: “Hello C#”, “20001”

Backslash character literalC# supports some special character constants that are used in output methods. The character combinations are called escape sequences.

Literals, Variables and Data Types

Literals, Variables and Data TypesVariableA variable is a identifier that denotes a storage location used to store a value. Unlike constants that remain unchanged during execution of a program, a variable may take different values at different times of execution.

Every variable has a type that determines what values can be stored in the variable.

Literals, Variables and Data TypesA Variable name can be chosen by the programmer in a meaningful way so as to reflect what it represents

Ex: average, total_height, height, classStrength

Rules for naming variables1. They must not begin with digit.2. Uppercase and lowercases are distinct.3. It should not be a keyword.4. Whitespace is not allowed.5. Variable names can be of any length.

Literals, Variables and Data TypesData TypesEvery Variable in C# is associated with data type.Data type will specify a size and type of values that can be stored in C#. C# language is rich in data types.

The types in C# are primarily divided into two categories.a. Value Types b. Reference Types

Literals, Variables and Data TypesValue Types and Reference Types differ in two characteristics:

a. Where they will be storedb. How they behave in context of assignment

statements.

Value types (which are of fixed length) are stored on the stack, and when a value of variable is assigned to another variable the value is actually copied. This means that two identical copies of same value are available in memory

Literals, Variables and Data TypesReference types (which are of variable length) are stored on heap, and when assignment happen between two reference variables occur, only the reference is copied, the actual remains in the same memory location.

This means that there are two references for a single value.

A third category of types called pointers is available for use only in unsafe code.

Literals, Variables and Data TypesValue types and reference types are further classified into predefined and user-defined data types;

Literals, Variables and Data TypesThe value types of C# can be grouped into two categories.a. User defined types (complex types) and b. Predefined types (simple types)

We can define complex typesknown as user-defined typeswhich include structs and enumerations.

Literals, Variables and Data TypesPredefined value types are also known as simple types (or primitive types) are further subdivided into: Numeric types Boolean types Character types

Numeric types includes integral types, floating-point types and decimal types.

C# 2.0 added a new type called nullable type. This type of variable can hold an undefined value.

Literals, Variables and Data TypesIntegral Types

Integral types can hold whole numbers such as 123, -96 and 5639. The size of the values that can be stored depends on the integral type we choose.

Literals, Variables and Data TypesSigned integers can hold both positive and negative numbers.

It should be remembered that wider data types require more time for manipulation and therefore it is advisable to use smaller data types.

Literals, Variables and Data TypesUnsigned integersWe can increase positive value stored in an integer by making it “unsigned”. For example, a 16-bit short integer can store values in the range -32,768 to 32,767. However making it ushort, it can handle values in the range of 0 to 65,535.

Literals, Variables and Data TypesFloating point typesIntegers only hold whole numbers and therefore we use another type known as Floating point type to hold numbers containing fractional parts such as 27.50 and -17.67.

There are two types of floating point types in C#.The float type value with single precision numbers with a precision of seven digits . The double type represents with double precision numbers with a precision of 15/16 digits.

Literals, Variables and Data Types

Literals, Variables and Data TypesFloating point numbers are by default are double precision numbers. To force them to be in single precision, we have to append them f or F before the number.Ex: 1.71f or 1.71F

Double precision are used when we need greater precision in storage of floating point numbers.

Literals, Variables and Data TypesFloating point data types support a special value known as NaN (Not a Number). This is used to represent the result of operations such as dividing by zero, where actual value is not produced, etc.

Literals, Variables and Data TypesDecimal typeThe decimal type is a high precision, 128-bit data type i.e. designed for use in financial and monetary calculations. It can store the values in the range of 1X1028 to 7X1028 with 28 significant digits.

To specify a decimal number we must append M to the number

For ex: 123.45M and this will be treated as double.

Literals, Variables and Data TypesCharacter typeIn order to store single characters in memory, c# provides a data type called char. The char type assumes a size of two bytes but, in fact it holds only single character.

Boolean typeBoolean type is used when we want to test a particular condition during execution of a program. Thereby only two values are allowed for boolean type either true or false.

Literals, Variables and Data TypesReference typesAs with value types, reference types can also be divided into two groups;User-defined reference types to those types which we define using predefined reference types

Ex: Classes, Delegates, Interface and Arrays.

Literals, Variables and Data TypesPredefined reference types which includeObjects and Strings

The object type is ultimate base type of all the intrinsic and user defined types in C#. We can use an object reference to bind an object of any particular type.

C# provides its own string type for creating and manipulating strings.

Literals, Variables and Data TypesDeclaration of variablesVariables are the names of storage locations.After designing suitable variable names, we must declare them to compiler.

Declaration does three things.It tell the compiler what the variable name isIt specifies what type of data type variable can hold.The place of declaration tells the scope of the variable.

Literals, Variables and Data TypesA variable must be declared before it is used in the program.

A variable can be used to store a value of any data type.

The general form of declaration of variable isType variable1, variable2, …. , variablen.

Variables are separated by commas if it is written in single line.

For ex: int count;Float r; etc

Literals, Variables and Data TypesInitialization of variablesA variable must be given a value after it has been declared and before it is used in an expression.

A simple method of providing value to variable is through assignment statement.int value=0;Final value=100;Yes=‘x’;

Literals, Variables and Data TypesThe process of providing initial values for variables is known as initialization.

The following are valid statementsFloat x,y,z;Int m=5,n=10;

This takes the form Type variablename=value;

Literals, Variables and Data TypesDefault Values

A Variable is either explicitly assigned value or automatically assigned a default value.

The following categories of variables are automatically initialized to their default values.• Static variables• Instance variables• Array elements

Literals, Variables and Data TypesThe default value of a variable depends on the type of variable

Literals, Variables and Data TypesConstant Variables

The variables whose value do not change during the execution of a program are known as constant variables.

For example, the variables representing the maximum number of rows and columns of a matrix or number of students in a class in a program may not change during execution of the program.

Literals, Variables and Data TypesEx: const int ROWS=10; const int COLS=20; const int NUM=90;

constants must be declared and initialized simultaneously For example const int m; m=100; This is illegal in C#.

Literals, Variables and Data TypesA constant variable can be initialized using expression

const int m=10; const int n=m*5;We cannot use non-const values in expressions.For instance, int m=10; const int =m*5; will result an error.

Literals, Variables and Data TypesAdvantages of using constants are

They make our programs easier to read and understand.

They make our programs easier to modify. They minimize accidental errors, like

attempting to assign values to some variables which are expected to be constants.

Literals, Variables and Data TypesNote about constants The names of the constants take same form

as variable names. After declaration of constants, they should

not be assigned any other value. Constants are declared for types. This is not

done in C or C++. Constants cannot be declared inside a

method. They should be declared only at class level.

Literals, Variables and Data TypesScope of Variables

The scope of a variable is the region of code within which the variable can be accessed.

This depends on the type of variable and place of its declaration. C# defines several categories of variables. They include

a. Static Variables b. Instance Variablesc. Array elementsd. Value Parameterse. Reference Parametersf. Output Parametersg. Local Variables.

Literals, Variables and Data TypesConsider the code shown below:Class ABC{ static int m; int n; void fun(int x, ref int y, out int z, int [ ] a) { int j=10; ------ -------}}

Literals, Variables and Data TypesThis code contain following variablesa. m is a static variableb. n as instance Variablec. a[0] as array elementd. x as value Parametere. y is a reference Parameterf. z as output Parameterg. j as local Variables.

Static and instance variables are declared at the class level and or known as fields or field variables.

Literals, Variables and Data TypesThe scope of these variables begins the place of their declaration and ends when the Main method terminates.

The variables x, y and z are the parameters of the method fun(). The value parameter x will exist till the end of the program.

The reference and output parameters (y and z) do not create new storage locations. Instead they represent the same locations as the variables that are passed arguments.

Literals, Variables and Data TypesThe elements of array such as a[0] come into existence when an array instance is created and cease to exist when there are no references.

Variables declared inside the methods are called local variables. Local variables can also be declared inside the program blocks that are defined between { and }.

Inside the same block it is an error declare a local variable with same name where another variable have same name.

Literals, Variables and Data TypesEx:

Literals, Variables and Data TypesEx:

Literals, Variables and Data TypesBoxing and UnboxingIn object-oriented programming, methods are invoked using objects.

Since value types of such as int and long are not objects, we cannot use them to call methods. C# enables us to achieve this through a technique called Boxing.

Literals, Variables and Data TypesBoxing means the conversion of a value type on the stack to an object type on the heap. Conversely the conversion from an object type back to a value type is known as unboxing.

Literals, Variables and Data TypesBoxing

Any type, value or reference can be assigned to an object without an explicit conversion. When the compiler finds a value type where it needs a reference type.

It creates an object ‘box’ into which it places the value of value type. The following illustrates this:

Literals, Variables and Data TypesWhen executed this code creates a temporary reference_type box for the object on the heap. We can use c stype cast for boxing

Note that boxing operation creates a copy of the value of m integer to the object om. Now both the variables m and om exist but value of om resides on the heap. These values are independent of each other.

Literals, Variables and Data TypesWhen the code changes the value of m, the value of om is not affected.

Literals, Variables and Data TypesUnboxing

Unboxing is the process of converting object type back to the value type.

Remember that we can only unbox a variable that has previously been boxed. In contrast to boxing, unboxing is an explicit operation using c-style casting

Literals, Variables and Data TypesWhen performing unboxing, C# checks that value type we request is actually stored in the object under conversion. Only if it is the value is unboxed.

When unboxing a value, we have to ensure that value type is large enough to hold the value of the object. Otherwise operation may result in runtime error.