SlideShare uma empresa Scribd logo
1 de 30
@ 2010 Tata McGraw-Hill Education
1
Education
Literals, Variables and Data TypesLiterals, Variables and Data Types
@ 2010 Tata McGraw-Hill Education
2
Education
Introduction
A C# program is basically a collection of classes. A class is defi ned by a set
of declaration statements and methods containing instructions known as
executable statements. These instructions are formed using certain
symbols and words according to some rigid rules known as syntax rules (or
grammar). The smallest, non-reducible, textual elements in a program are
referred to as tokens. The compiler recognizes them for building up
expressions and statements. In simple terms, a C# program is a collection of
tokens, comments and white spaces. C# includes the following five types of
tokens:Keywords
Operators
 Identifiers
Punctuators
Literals
White spaces and comments are not tokens, though they may act as
separators for tokens. Keywords are an essential part of a language defi
nition. They implement specific features of the language. They are
reserved, and cannot be used as identifiers except when they are prefaced
by the @ character
@ 2010 Tata McGraw-Hill Education
3
Education
Identifiers are programmer-designed tokens. They are used for naming
classes, methods, variables, labels, namespaces, interfaces, etc. C# identifiers
enforce the following rules:
They can have alphabets, digits and underscore characters
They must not begin with a digit
Upper case and lower case letters are distinct
Keywords in stand-alone mode cannot be used as identifiers
Literals are the way in which the values that are stored in variables are
represented. We shall discuss these in detail in the next section
@ 2010 Tata McGraw-Hill Education
4
Education
Operators are symbols used in expressions to describe operations involving
one or more operands. Operators are considered in detail in Chapter 5.
Punctuators are symbols used for grouping and separating code. They defi
ne the shape and function of a program. Punctuators (also known as
separators) in C# include:
Parentheses ( )
Braces { }
Brackets [ ]
Semicolons ;
Colon:
Comma ,
Period .
@ 2010 Tata McGraw-Hill Education
5
Education
LITERALS
Literals are value constants assigned to variables (or results of expressions) in a
program. C# supports several types of literals as illustrated in Fig. 4.1.
@ 2010 Tata McGraw-Hill Education
6
Education
Integer Literals
An integer literal refers to a sequence of digits. There are two types of integers,
namely, decimal integers and hexadecimal integers.
Decimal integers consist of a set of digits, 0 through 9, preceded by an optional minus
sign. Valid examples of decimal integer literals are:
123 -321 0 654321
Embedded spaces, commas and non-digit characters are not permitted between digits.
For example, 15 750 20,000 $1000 are illegal numbers.
A sequence of digits preceded by 0x or 0X is considered as a hexadecimal integer (hex
integer). It may also include alphabets A through F or ‘a’ through ‘f’. A letter A
through F represents the numbers 10 through 15. Following are the examples of valid
hex integers. 0X2 0X9F 0Xbcd 0x
@ 2010 Tata McGraw-Hill Education
7
Education
Real 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. Further examples of real literals are:
0.0083 -0.75 435.36
These numbers are shown in decimal notation, having a whole number followed by a
decimal point and the fractional part, which is an integer. It is possible that the number
may not have digits before the decimal point, or digits after the decimal point. That is,
215. .95 -.71 are all valid real literals.
Boolean Literals
There are two Boolean literal values:
True False
They are used as values of relational expressions.
@ 2010 Tata McGraw-Hill Education
8
Education
Single Character Literals
A single-character literal (or simply character constant) contains a single character
enclosed within a pair of single quote marks. Example of character in the examples
above constants are:
‘5’ ‘X’ ‘;’ ‘ ‘
Note that the character constant ‘5’ is not the same as the number 5. The last constant in
the example above is a blank space.
String Literals
A string literal is a sequence of characters enclosed between double quotes.The
characters may be alphabets, digits, special characters and blank spaces. Examples
are:
“Hello C#” “2001” “WELL DONE” “?...!” “5+3” “X”
@ 2010 Tata McGraw-Hill Education
9
Education
Backslash Character Literal
C# supports some special backslash character constants that are used in output methods.
For example, the symbol ‘n’ stands for a new-line character. A list of such backslash
character literals is given in Table 4.2. Note that each one
represents one character, although they consist of two characters. These character
combinations are known as escape sequences.
@ 2010 Tata McGraw-Hill Education
10
Education
Program 4.2 prints the various numeric literals available in C#, such as Integer,
Double and Exponential.
@ 2010 Tata McGraw-Hill Education
11
Education
VARIABLES
A variable is an identifier that denotes a storage location used to store a data value.
Unlike constants that remain unchanged during the execution of a program, a variable
may take different values at different times during the execution of the program.
Every variable has a type that determines what values can
be stored in the variable. A variable name can be chosen by the programmer in a
meaningful way so as to reflect what it represents in the program. Some examples of
variable names are:
average
height
total_height
Class Strength
@ 2010 Tata McGraw-Hill Education
12
Education
As mentioned earlier, variable names may consist of alphabets, digits and the
underscore ( _ ), subject to the following conditions:
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct. This means that the variable Total is
not the same as total or TOTAL.
3. It should not be a keyword.
4. White space is not allowed.
5. Variable names can be of any length.
@ 2010 Tata McGraw-Hill Education
13
Education
DATA TYPES
Data types specify the size and type of values that can be stored. C# is a language rich
in its data types. The variety available allows the programmer to
select the type appropriate to the needs of the application. The types in C# are
primarily divided into two categories:
Value types
Reference types
Value types and reference types differ in two characteristics:
Where they are stored in the memory
How they behave in the context of assignment statements
@ 2010 Tata McGraw-Hill Education
14
Education
@ 2010 Tata McGraw-Hill Education
15
Education
VALUE TYPES
The value types of C# can be grouped into two categories (as shown in Fig. 4.2),
namely,
User-defined types (or complex types) and
Predefined types (or simple types)
We can define our own complex types known as user-defined value types which
include struct types and enumerations. They are discussed in Chapter 11. Predefined
value types which are also known as simple types (or primitive types) are further
subdivided into:
Numeric types,
Boolean types, and
Character types.
@ 2010 Tata McGraw-Hill Education
16
Education
Note: C# 2.0 added a new type
called nullable type. This type
variable can hold an undefined value
Any value type variable can be defined
as a nullable type.
@ 2010 Tata McGraw-Hill Education
17
Education
Integral 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 data type we choose. C# supports the
concept of unsigned types and therefore it supports eight types of integers as shown in
Figs 4.4 and 4.5.
@ 2010 Tata McGraw-Hill Education
18
Education
Signed Integers
Signed integer types can hold both positive and negative numbers. Table 4.3 shows
the memory size and range of all the four signed integer data types.(Note that one byte
is equal to eight bits).
@ 2010 Tata McGraw-Hill Education
19
Education
Unsigned Integers
We can increase the size of the positive value stored in an integer type by making it
‘unsigned’. For example, a 16-bit short integer can store values in the range –32,768 to
32,767. However, by making it ushort, it can handle values in the range 0 to 65,535.
Table 4.4 shows the size and range of all the four unsigned integer data types.
@ 2010 Tata McGraw-Hill Education
20
Education
Floating-Point Types
Integer types can hold only whole numbers and therefore we use another type known
as fl oating-point type to hold numbers containing fractional parts such as 27.59 and –
1.375. There are two kinds of fl oating point storage in C#
as shown in Fig. 4.6.
@ 2010 Tata McGraw-Hill Education
21
Education
Decimal Type
The decimal type is a high precision, 128-bit data type that is designed for use in
financial and monetary calculations. It can store values in the range 1.0 ∞ 10–28 to 7.9
∞ 1028 with 28 significant digits. Note that the precision is given in digits, not in
decimal places.
Character Type
In order to store single characters in memory, C# provides a character data type called
char. The char type assumes a size of two bytes but, in fact it can hold only a single
character. It has been designed to hold a 16-bit Unicode character, in which the 8-bit
ASCII code is a subset.
Boolean Type
Boolean type is used when we want to test a particular condition during the execution
of the program. There are only two values that a Boolean type can take: true or
false. Remember, both these words have been declared as keywords.
@ 2010 Tata McGraw-Hill Education
22
Education
REFERENCE TYPES
As with value types, the reference types can also be divided into two groups:
User-defined (or complex types)
Predefined (or simple types)
User-defined reference types refer to those types which we define using predefi ned
types. They include:
Classes
Delegates
Interfaces
Arrays
These complex types will be discussed in later chapters when we take up these topics
individually. Predefined reference types include two data types:
Object type String type
@ 2010 Tata McGraw-Hill Education
23
Education
DECLARATION OF VARIABLES
Variables are the names of storage locations. After designing suitable variable names,
we must declare them to the compiler. Declaration does three things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
3. The place of declaration (in the program) decides the scope of the variable.
A variable must be declared before it is used in the program.
The general form of declaration of a variable is:
type Variable1, Variable2, ……VariableN;
Variables are separated by commas, A declaration statement must end with a
semicolon.
@ 2010 Tata McGraw-Hill Education
24
Education
INITIALIZATION OF VARIABLES
A variable must be given a value after it has been declared but before it is used in an
expression. A simple method of giving value to a variable is through the assignment
statement as follows: variableName = value;
Examples:
initial Value = O;
final Value = 100;
yes = ‘x’;
DEFAULT VALUES
A variable is either explicitly assigned a 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
@ 2010 Tata McGraw-Hill Education
25
Education
@ 2010 Tata McGraw-Hill Education
26
Education
CONSTANT VARIABLES
The variables whose values do not change during the execution of a program are
known as constants. 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. Such variables can be made unmodifiable by
using the const keyword while initializing them.
Example:
const int ROWS = 10;
const int COLS = 20;
const int NUM = 90
@ 2010 Tata McGraw-Hill Education
27
Education
SCOPE 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 the variable and place of its declaration. C#
defines several categories of variables. They include:
Static variables
Instance variables
Array elements
Value parameters
Reference parameters
Output parameters
Local variables
@ 2010 Tata McGraw-Hill Education
28
Education
This code contains the following variables:
m as a static variable
n as an instance variable
x as a value parameter
y as a reference parameter
z as an output parameter
a[0] as an array element
j as a local variable
Static and instance variables are declared at the class level and are known as fields or
field variables. The scope of these variables begins at the place of their declaration
and ends when the Main method terminates.
@ 2010 Tata McGraw-Hill Education
29
Education
BOXING AND UNBOXING
In object-oriented programming, methods are invoked using objects. Since value types
such as int and long are not objects, we cannot use them to call methods. C# enables
us to achieve this through a technique known as boxing .
Boxing
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 the value type. The following
code illustrates boxing:
int m = 100;
object om = m; // creates a box to hold m
When executed, this code creates a temporary reference_type ‘box’ for the object on
heap. We can also use a C-style cast for boxing.
int m = 100;
object om = m; // creates a box to hold m
@ 2010 Tata McGraw-Hill Education
30
Education
Unboxing
Unboxing is the process of converting the 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
int m = 10;
object om = m; //box m
int n = (int)om; //unbox om back to an int
When unboxing a value, we have to ensure that the value type is large enough to hold
the value of the object. Otherwise, the operation may result in a runtime error. For
example, the code
int m = 500;
object om = m;
byte n = (byte)om;

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Structure and Enum in c#
Structure and Enum in c#Structure and Enum in c#
Structure and Enum in c#
 
python conditional statement.pptx
python conditional statement.pptxpython conditional statement.pptx
python conditional statement.pptx
 
inheritance c++
inheritance c++inheritance c++
inheritance c++
 
Basics of c++
Basics of c++Basics of c++
Basics of c++
 
Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
C functions
C functionsC functions
C functions
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
String c
String cString c
String c
 
C++ presentation
C++ presentationC++ presentation
C++ presentation
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
Classes and Objects in C#
Classes and Objects in C#Classes and Objects in C#
Classes and Objects in C#
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Difference between Java and c#
Difference between Java and c#Difference between Java and c#
Difference between Java and c#
 
C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#
 
C# basics
 C# basics C# basics
C# basics
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Types of function call
Types of function callTypes of function call
Types of function call
 

Semelhante a Literals,variables,datatype in C#

Module 1:Introduction
Module 1:IntroductionModule 1:Introduction
Module 1:Introductionnikshaikh786
 
Constants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiConstants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiSowmyaJyothi3
 
Fundamentals of C Programming Language
Fundamentals of C Programming LanguageFundamentals of C Programming Language
Fundamentals of C Programming LanguageRamaBoya2
 
PROGRAMMING IN C - Inroduction.pptx
PROGRAMMING IN C - Inroduction.pptxPROGRAMMING IN C - Inroduction.pptx
PROGRAMMING IN C - Inroduction.pptxNithya K
 
C the basic concepts
C the basic conceptsC the basic concepts
C the basic conceptsAbhinav Vatsa
 
Dot net programming concept
Dot net  programming conceptDot net  programming concept
Dot net programming conceptsandeshjadhav28
 
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdfL2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdfMMRF2
 
Data Types and Variables In C Programming
Data Types and Variables In C ProgrammingData Types and Variables In C Programming
Data Types and Variables In C ProgrammingKamal Acharya
 
Basic of the C language
Basic of the C languageBasic of the C language
Basic of the C languageSachin Verma
 
Data Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingData Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingSherwin Banaag Sapin
 
Structure of c_program_to_input_output
Structure of c_program_to_input_outputStructure of c_program_to_input_output
Structure of c_program_to_input_outputAnil Dutt
 
C programming Training in Ambala ! Batra Computer Centre
C programming Training in Ambala ! Batra Computer CentreC programming Training in Ambala ! Batra Computer Centre
C programming Training in Ambala ! Batra Computer Centrejatin batra
 

Semelhante a Literals,variables,datatype in C# (20)

Module 1:Introduction
Module 1:IntroductionModule 1:Introduction
Module 1:Introduction
 
Data type
Data typeData type
Data type
 
PSPC--UNIT-2.pdf
PSPC--UNIT-2.pdfPSPC--UNIT-2.pdf
PSPC--UNIT-2.pdf
 
Constants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiConstants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya Jyothi
 
C Slides
C SlidesC Slides
C Slides
 
Fundamentals of C Programming Language
Fundamentals of C Programming LanguageFundamentals of C Programming Language
Fundamentals of C Programming Language
 
PROGRAMMING IN C - Inroduction.pptx
PROGRAMMING IN C - Inroduction.pptxPROGRAMMING IN C - Inroduction.pptx
PROGRAMMING IN C - Inroduction.pptx
 
C the basic concepts
C the basic conceptsC the basic concepts
C the basic concepts
 
Dot net programming concept
Dot net  programming conceptDot net  programming concept
Dot net programming concept
 
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdfL2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
 
C tokens
C tokensC tokens
C tokens
 
Basics of C.ppt
Basics of C.pptBasics of C.ppt
Basics of C.ppt
 
Data Types and Variables In C Programming
Data Types and Variables In C ProgrammingData Types and Variables In C Programming
Data Types and Variables In C Programming
 
Basic of the C language
Basic of the C languageBasic of the C language
Basic of the C language
 
Data Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingData Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# Programming
 
Basics of c
Basics of cBasics of c
Basics of c
 
Structure of c_program_to_input_output
Structure of c_program_to_input_outputStructure of c_program_to_input_output
Structure of c_program_to_input_output
 
Aniket tore
Aniket toreAniket tore
Aniket tore
 
5 introduction-to-c
5 introduction-to-c5 introduction-to-c
5 introduction-to-c
 
C programming Training in Ambala ! Batra Computer Centre
C programming Training in Ambala ! Batra Computer CentreC programming Training in Ambala ! Batra Computer Centre
C programming Training in Ambala ! Batra Computer Centre
 

Mais de Prasanna Kumar SM

Mais de Prasanna Kumar SM (6)

C# Introduction brief
C# Introduction briefC# Introduction brief
C# Introduction brief
 
Overview of c#
Overview of c#Overview of c#
Overview of c#
 
Operators and Expressions in C#
Operators and Expressions in C#Operators and Expressions in C#
Operators and Expressions in C#
 
Decision making and loop in C#
Decision making and loop in C#Decision making and loop in C#
Decision making and loop in C#
 
Characteristics of c#
Characteristics of c#Characteristics of c#
Characteristics of c#
 
C# intro
C# introC# intro
C# intro
 

Último

ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsManeerUddin
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 

Último (20)

ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture hons
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 

Literals,variables,datatype in C#

  • 1. @ 2010 Tata McGraw-Hill Education 1 Education Literals, Variables and Data TypesLiterals, Variables and Data Types
  • 2. @ 2010 Tata McGraw-Hill Education 2 Education Introduction A C# program is basically a collection of classes. A class is defi ned by a set of declaration statements and methods containing instructions known as executable statements. These instructions are formed using certain symbols and words according to some rigid rules known as syntax rules (or grammar). The smallest, non-reducible, textual elements in a program are referred to as tokens. The compiler recognizes them for building up expressions and statements. In simple terms, a C# program is a collection of tokens, comments and white spaces. C# includes the following five types of tokens:Keywords Operators  Identifiers Punctuators Literals White spaces and comments are not tokens, though they may act as separators for tokens. Keywords are an essential part of a language defi nition. They implement specific features of the language. They are reserved, and cannot be used as identifiers except when they are prefaced by the @ character
  • 3. @ 2010 Tata McGraw-Hill Education 3 Education Identifiers are programmer-designed tokens. They are used for naming classes, methods, variables, labels, namespaces, interfaces, etc. C# identifiers enforce the following rules: They can have alphabets, digits and underscore characters They must not begin with a digit Upper case and lower case letters are distinct Keywords in stand-alone mode cannot be used as identifiers Literals are the way in which the values that are stored in variables are represented. We shall discuss these in detail in the next section
  • 4. @ 2010 Tata McGraw-Hill Education 4 Education Operators are symbols used in expressions to describe operations involving one or more operands. Operators are considered in detail in Chapter 5. Punctuators are symbols used for grouping and separating code. They defi ne the shape and function of a program. Punctuators (also known as separators) in C# include: Parentheses ( ) Braces { } Brackets [ ] Semicolons ; Colon: Comma , Period .
  • 5. @ 2010 Tata McGraw-Hill Education 5 Education LITERALS Literals are value constants assigned to variables (or results of expressions) in a program. C# supports several types of literals as illustrated in Fig. 4.1.
  • 6. @ 2010 Tata McGraw-Hill Education 6 Education Integer Literals An integer literal refers to a sequence of digits. There are two types of integers, namely, decimal integers and hexadecimal integers. Decimal integers consist of a set of digits, 0 through 9, preceded by an optional minus sign. Valid examples of decimal integer literals are: 123 -321 0 654321 Embedded spaces, commas and non-digit characters are not permitted between digits. For example, 15 750 20,000 $1000 are illegal numbers. A sequence of digits preceded by 0x or 0X is considered as a hexadecimal integer (hex integer). It may also include alphabets A through F or ‘a’ through ‘f’. A letter A through F represents the numbers 10 through 15. Following are the examples of valid hex integers. 0X2 0X9F 0Xbcd 0x
  • 7. @ 2010 Tata McGraw-Hill Education 7 Education Real 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. Further examples of real literals are: 0.0083 -0.75 435.36 These numbers are shown in decimal notation, having a whole number followed by a decimal point and the fractional part, which is an integer. It is possible that the number may not have digits before the decimal point, or digits after the decimal point. That is, 215. .95 -.71 are all valid real literals. Boolean Literals There are two Boolean literal values: True False They are used as values of relational expressions.
  • 8. @ 2010 Tata McGraw-Hill Education 8 Education Single Character Literals A single-character literal (or simply character constant) contains a single character enclosed within a pair of single quote marks. Example of character in the examples above constants are: ‘5’ ‘X’ ‘;’ ‘ ‘ Note that the character constant ‘5’ is not the same as the number 5. The last constant in the example above is a blank space. String Literals A string literal is a sequence of characters enclosed between double quotes.The characters may be alphabets, digits, special characters and blank spaces. Examples are: “Hello C#” “2001” “WELL DONE” “?...!” “5+3” “X”
  • 9. @ 2010 Tata McGraw-Hill Education 9 Education Backslash Character Literal C# supports some special backslash character constants that are used in output methods. For example, the symbol ‘n’ stands for a new-line character. A list of such backslash character literals is given in Table 4.2. Note that each one represents one character, although they consist of two characters. These character combinations are known as escape sequences.
  • 10. @ 2010 Tata McGraw-Hill Education 10 Education Program 4.2 prints the various numeric literals available in C#, such as Integer, Double and Exponential.
  • 11. @ 2010 Tata McGraw-Hill Education 11 Education VARIABLES A variable is an identifier that denotes a storage location used to store a data value. Unlike constants that remain unchanged during the execution of a program, a variable may take different values at different times during the execution of the program. Every variable has a type that determines what values can be stored in the variable. A variable name can be chosen by the programmer in a meaningful way so as to reflect what it represents in the program. Some examples of variable names are: average height total_height Class Strength
  • 12. @ 2010 Tata McGraw-Hill Education 12 Education As mentioned earlier, variable names may consist of alphabets, digits and the underscore ( _ ), subject to the following conditions: 1. They must not begin with a digit. 2. Uppercase and lowercase are distinct. This means that the variable Total is not the same as total or TOTAL. 3. It should not be a keyword. 4. White space is not allowed. 5. Variable names can be of any length.
  • 13. @ 2010 Tata McGraw-Hill Education 13 Education DATA TYPES Data types specify the size and type of values that can be stored. C# is a language rich in its data types. The variety available allows the programmer to select the type appropriate to the needs of the application. The types in C# are primarily divided into two categories: Value types Reference types Value types and reference types differ in two characteristics: Where they are stored in the memory How they behave in the context of assignment statements
  • 14. @ 2010 Tata McGraw-Hill Education 14 Education
  • 15. @ 2010 Tata McGraw-Hill Education 15 Education VALUE TYPES The value types of C# can be grouped into two categories (as shown in Fig. 4.2), namely, User-defined types (or complex types) and Predefined types (or simple types) We can define our own complex types known as user-defined value types which include struct types and enumerations. They are discussed in Chapter 11. Predefined value types which are also known as simple types (or primitive types) are further subdivided into: Numeric types, Boolean types, and Character types.
  • 16. @ 2010 Tata McGraw-Hill Education 16 Education Note: C# 2.0 added a new type called nullable type. This type variable can hold an undefined value Any value type variable can be defined as a nullable type.
  • 17. @ 2010 Tata McGraw-Hill Education 17 Education Integral 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 data type we choose. C# supports the concept of unsigned types and therefore it supports eight types of integers as shown in Figs 4.4 and 4.5.
  • 18. @ 2010 Tata McGraw-Hill Education 18 Education Signed Integers Signed integer types can hold both positive and negative numbers. Table 4.3 shows the memory size and range of all the four signed integer data types.(Note that one byte is equal to eight bits).
  • 19. @ 2010 Tata McGraw-Hill Education 19 Education Unsigned Integers We can increase the size of the positive value stored in an integer type by making it ‘unsigned’. For example, a 16-bit short integer can store values in the range –32,768 to 32,767. However, by making it ushort, it can handle values in the range 0 to 65,535. Table 4.4 shows the size and range of all the four unsigned integer data types.
  • 20. @ 2010 Tata McGraw-Hill Education 20 Education Floating-Point Types Integer types can hold only whole numbers and therefore we use another type known as fl oating-point type to hold numbers containing fractional parts such as 27.59 and – 1.375. There are two kinds of fl oating point storage in C# as shown in Fig. 4.6.
  • 21. @ 2010 Tata McGraw-Hill Education 21 Education Decimal Type The decimal type is a high precision, 128-bit data type that is designed for use in financial and monetary calculations. It can store values in the range 1.0 ∞ 10–28 to 7.9 ∞ 1028 with 28 significant digits. Note that the precision is given in digits, not in decimal places. Character Type In order to store single characters in memory, C# provides a character data type called char. The char type assumes a size of two bytes but, in fact it can hold only a single character. It has been designed to hold a 16-bit Unicode character, in which the 8-bit ASCII code is a subset. Boolean Type Boolean type is used when we want to test a particular condition during the execution of the program. There are only two values that a Boolean type can take: true or false. Remember, both these words have been declared as keywords.
  • 22. @ 2010 Tata McGraw-Hill Education 22 Education REFERENCE TYPES As with value types, the reference types can also be divided into two groups: User-defined (or complex types) Predefined (or simple types) User-defined reference types refer to those types which we define using predefi ned types. They include: Classes Delegates Interfaces Arrays These complex types will be discussed in later chapters when we take up these topics individually. Predefined reference types include two data types: Object type String type
  • 23. @ 2010 Tata McGraw-Hill Education 23 Education DECLARATION OF VARIABLES Variables are the names of storage locations. After designing suitable variable names, we must declare them to the compiler. Declaration does three things: 1. It tells the compiler what the variable name is. 2. It specifies what type of data the variable will hold. 3. The place of declaration (in the program) decides the scope of the variable. A variable must be declared before it is used in the program. The general form of declaration of a variable is: type Variable1, Variable2, ……VariableN; Variables are separated by commas, A declaration statement must end with a semicolon.
  • 24. @ 2010 Tata McGraw-Hill Education 24 Education INITIALIZATION OF VARIABLES A variable must be given a value after it has been declared but before it is used in an expression. A simple method of giving value to a variable is through the assignment statement as follows: variableName = value; Examples: initial Value = O; final Value = 100; yes = ‘x’; DEFAULT VALUES A variable is either explicitly assigned a 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
  • 25. @ 2010 Tata McGraw-Hill Education 25 Education
  • 26. @ 2010 Tata McGraw-Hill Education 26 Education CONSTANT VARIABLES The variables whose values do not change during the execution of a program are known as constants. 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. Such variables can be made unmodifiable by using the const keyword while initializing them. Example: const int ROWS = 10; const int COLS = 20; const int NUM = 90
  • 27. @ 2010 Tata McGraw-Hill Education 27 Education SCOPE 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 the variable and place of its declaration. C# defines several categories of variables. They include: Static variables Instance variables Array elements Value parameters Reference parameters Output parameters Local variables
  • 28. @ 2010 Tata McGraw-Hill Education 28 Education This code contains the following variables: m as a static variable n as an instance variable x as a value parameter y as a reference parameter z as an output parameter a[0] as an array element j as a local variable Static and instance variables are declared at the class level and are known as fields or field variables. The scope of these variables begins at the place of their declaration and ends when the Main method terminates.
  • 29. @ 2010 Tata McGraw-Hill Education 29 Education BOXING AND UNBOXING In object-oriented programming, methods are invoked using objects. Since value types such as int and long are not objects, we cannot use them to call methods. C# enables us to achieve this through a technique known as boxing . Boxing 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 the value type. The following code illustrates boxing: int m = 100; object om = m; // creates a box to hold m When executed, this code creates a temporary reference_type ‘box’ for the object on heap. We can also use a C-style cast for boxing. int m = 100; object om = m; // creates a box to hold m
  • 30. @ 2010 Tata McGraw-Hill Education 30 Education Unboxing Unboxing is the process of converting the 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 int m = 10; object om = m; //box m int n = (int)om; //unbox om back to an int When unboxing a value, we have to ensure that the value type is large enough to hold the value of the object. Otherwise, the operation may result in a runtime error. For example, the code int m = 500; object om = m; byte n = (byte)om;