SlideShare a Scribd company logo
1 of 6
Download to read offline
Generated by Foxit PDF Creator © Foxit Software
                                                   http://www.foxitsoftware.com For evaluation only.




                         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


                                                Page 1 of 6
Generated by Foxit PDF Creator © Foxit Software
                                                http://www.foxitsoftware.com For evaluation only.




Prof. Mukesh N. Tekwani                                        Email: mukeshtekwani@hotmail.com

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

bool                            break             const
byte                            case              false
char                            catch             in
decimal                         class             new
double                          continue          null
float                           do                object
int                             else              private
long                            for               public
sbyte                           foreach           return
short                           goto              struct
string                          if                true
ulong                           switch            void
ushort                          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.


                                             Page 2 of 6
Generated by Foxit PDF Creator © Foxit Software
                                                  http://www.foxitsoftware.com For evaluation only.




                                                                                    2. Programming in C#
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.

                                               Page 3 of 6
Generated by Foxit PDF Creator © Foxit Software
                                                 http://www.foxitsoftware.com For evaluation only.




Prof. Mukesh N. Tekwani                                         Email: mukeshtekwani@hotmail.com
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



                                              Page 4 of 6
Generated by Foxit PDF Creator © Foxit Software
                                                 http://www.foxitsoftware.com For evaluation only.




                                                                                   2. Programming in C#
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



                                               Page 5 of 6
Generated by Foxit PDF Creator © Foxit Software
                                                 http://www.foxitsoftware.com For evaluation only.




Prof. Mukesh N. Tekwani                                         Email: mukeshtekwani@hotmail.com


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.

                                              Page 6 of 6

More Related Content

What's hot

INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGAbhishek Dwivedi
 
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
 
Chapter1 c programming data types, variables and constants
Chapter1 c programming   data types, variables and constantsChapter1 c programming   data types, variables and constants
Chapter1 c programming data types, variables and constantsvinay arora
 
Programming in c
Programming in cProgramming in c
Programming in cvineet4523
 
C presentation book
C presentation bookC presentation book
C presentation bookkrunal1210
 
2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# isiragezeynu
 
DTS s03e04 Typing
DTS s03e04 TypingDTS s03e04 Typing
DTS s03e04 TypingTuenti
 
Learn C# Programming - Data Types & Type Conversion
Learn C# Programming - Data Types & Type ConversionLearn C# Programming - Data Types & Type Conversion
Learn C# Programming - Data Types & Type ConversionEng Teong Cheah
 
Introduction of c_language
Introduction of c_languageIntroduction of c_language
Introduction of c_languageSINGH PROJECTS
 
C# Value Data Types and Reference Data Types
C# Value Data Types and Reference Data TypesC# Value Data Types and Reference Data Types
C# Value Data Types and Reference Data TypesMicheal Ogundero
 
Chapter 13.1.3
Chapter 13.1.3Chapter 13.1.3
Chapter 13.1.3patcha535
 
Basic C Programming language
Basic C Programming languageBasic C Programming language
Basic C Programming languageAbhishek Soni
 
02. Data Type and Variables
02. Data Type and Variables02. Data Type and Variables
02. Data Type and VariablesTommy Vercety
 
Language tour of dart
Language tour of dartLanguage tour of dart
Language tour of dartImran Qasim
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm Madishetty Prathibha
 

What's hot (20)

INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
 
5 introduction-to-c
5 introduction-to-c5 introduction-to-c
5 introduction-to-c
 
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
 
Chapter1 c programming data types, variables and constants
Chapter1 c programming   data types, variables and constantsChapter1 c programming   data types, variables and constants
Chapter1 c programming data types, variables and constants
 
c# at f#
c# at f#c# at f#
c# at f#
 
Programming in c
Programming in cProgramming in c
Programming in c
 
C presentation book
C presentation bookC presentation book
C presentation book
 
2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
 
DTS s03e04 Typing
DTS s03e04 TypingDTS s03e04 Typing
DTS s03e04 Typing
 
LEARN C# PROGRAMMING WITH GMT
LEARN C# PROGRAMMING WITH GMTLEARN C# PROGRAMMING WITH GMT
LEARN C# PROGRAMMING WITH GMT
 
Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
 
Pc module1
Pc module1Pc module1
Pc module1
 
Learn C# Programming - Data Types & Type Conversion
Learn C# Programming - Data Types & Type ConversionLearn C# Programming - Data Types & Type Conversion
Learn C# Programming - Data Types & Type Conversion
 
Introduction of c_language
Introduction of c_languageIntroduction of c_language
Introduction of c_language
 
C# Value Data Types and Reference Data Types
C# Value Data Types and Reference Data TypesC# Value Data Types and Reference Data Types
C# Value Data Types and Reference Data Types
 
Chapter 13.1.3
Chapter 13.1.3Chapter 13.1.3
Chapter 13.1.3
 
Basic C Programming language
Basic C Programming languageBasic C Programming language
Basic C Programming language
 
02. Data Type and Variables
02. Data Type and Variables02. Data Type and Variables
02. Data Type and Variables
 
Language tour of dart
Language tour of dartLanguage tour of dart
Language tour of dart
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
 

Viewers also liked (7)

Perl Chapter 1
Perl Chapter 1Perl Chapter 1
Perl Chapter 1
 
OSI Model
OSI ModelOSI Model
OSI Model
 
Sql ch 1
Sql ch 1Sql ch 1
Sql ch 1
 
C sharp chap5
C sharp chap5C sharp chap5
C sharp chap5
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
Sql ch 15 - sql security
Sql ch 15 - sql securitySql ch 15 - sql security
Sql ch 15 - sql security
 
Ajax chap 5
Ajax chap 5Ajax chap 5
Ajax chap 5
 

Similar to C sharp chap2

C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...Rowank2
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)Shoaib Ghachi
 
Interview Questions For C Language
Interview Questions For C Language Interview Questions For C Language
Interview Questions For C Language Rowank2
 
Interview Questions For C Language .pptx
Interview Questions For C Language .pptxInterview Questions For C Language .pptx
Interview Questions For C Language .pptxRowank2
 
Basic Structure Of C++
Basic Structure Of C++Basic Structure Of C++
Basic Structure Of C++DevangiParekh1
 
A tour of C# - Overview _ Microsoft Learn.pdf
A tour of C# - Overview _ Microsoft Learn.pdfA tour of C# - Overview _ Microsoft Learn.pdf
A tour of C# - Overview _ Microsoft Learn.pdfParasJain570452
 
java handout.doc
java handout.docjava handout.doc
java handout.docSOMOSCO1
 
C and CPP Interview Questions
C and CPP Interview QuestionsC and CPP Interview Questions
C and CPP Interview QuestionsSagar Joshi
 
Variables in C and C++ Language
Variables in C and C++ LanguageVariables in C and C++ Language
Variables in C and C++ LanguageWay2itech
 
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
 
C programming notes.pdf
C programming notes.pdfC programming notes.pdf
C programming notes.pdfAdiseshaK
 
Introduction to c
Introduction to cIntroduction to c
Introduction to cAjeet Kumar
 

Similar to C sharp chap2 (20)

C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)
 
Interview Questions For C Language
Interview Questions For C Language Interview Questions For C Language
Interview Questions For C Language
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Interview Questions For C Language .pptx
Interview Questions For C Language .pptxInterview Questions For C Language .pptx
Interview Questions For C Language .pptx
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Basic Structure Of C++
Basic Structure Of C++Basic Structure Of C++
Basic Structure Of C++
 
A tour of C# - Overview _ Microsoft Learn.pdf
A tour of C# - Overview _ Microsoft Learn.pdfA tour of C# - Overview _ Microsoft Learn.pdf
A tour of C# - Overview _ Microsoft Learn.pdf
 
java handout.doc
java handout.docjava handout.doc
java handout.doc
 
C++ Basics
C++ BasicsC++ Basics
C++ Basics
 
C and CPP Interview Questions
C and CPP Interview QuestionsC and CPP Interview Questions
C and CPP Interview Questions
 
C programming notes
C programming notesC programming notes
C programming notes
 
Variables in C and C++ Language
Variables in C and C++ LanguageVariables in C and C++ Language
Variables in C and C++ Language
 
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
 
C programming notes.pdf
C programming notes.pdfC programming notes.pdf
C programming notes.pdf
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
venkatesh.pptx
venkatesh.pptxvenkatesh.pptx
venkatesh.pptx
 
Aniket tore
Aniket toreAniket tore
Aniket tore
 
Computer programming questions
Computer programming questionsComputer programming questions
Computer programming questions
 
Computer programming questions
Computer programming questionsComputer programming questions
Computer programming questions
 

More from Mukesh Tekwani

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelMukesh Tekwani
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfMukesh Tekwani
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - PhysicsMukesh Tekwani
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion Mukesh Tekwani
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Mukesh Tekwani
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversionMukesh Tekwani
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion Mukesh Tekwani
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversionMukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prismMukesh Tekwani
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surfaceMukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomMukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesMukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEMukesh Tekwani
 

More from Mukesh Tekwani (20)

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube Channel
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
 
Circular motion
Circular motionCircular motion
Circular motion
 
Gravitation
GravitationGravitation
Gravitation
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
 
XML
XMLXML
XML
 

C sharp chap2

  • 1. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 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 Page 1 of 6
  • 2. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani Email: mukeshtekwani@hotmail.com Keywords : C# has 76 keywords. A few commonly used keywords are listed below: bool break const byte case false char catch in decimal class new double continue null float do object int else private long for public sbyte foreach return short goto struct string if true ulong switch void ushort 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. Page 2 of 6
  • 3. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 2. Programming in C# 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. Page 3 of 6
  • 4. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani Email: mukeshtekwani@hotmail.com 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 Page 4 of 6
  • 5. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 2. Programming in C# 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 Page 5 of 6
  • 6. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani Email: mukeshtekwani@hotmail.com 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. Page 6 of 6