SlideShare ist ein Scribd-Unternehmen logo
1 von 71
Primitive DataPrimitive Data
Types andVariablesTypes andVariables
Creating and RunningYour First C# ProgramCreating and RunningYour First C# Program
Arshman SaleemArshman Saleem
A Tech & Software DevelopmentA Tech & Software Development
Table of ContentsTable of Contents
1.1. Primitive Data TypesPrimitive Data Types
 IntegerInteger
 Floating-Point / Decimal Floating-PointFloating-Point / Decimal Floating-Point
 BooleanBoolean
 CharacterCharacter
 StringString
 ObjectObject
1.1. Declaring and Using VariablesDeclaring and Using Variables
 IdentifiersIdentifiers
 Declaring Variables and Assigning ValuesDeclaring Variables and Assigning Values
 LiteralsLiterals
1.1. NullableNullable typestypes
2
Primitive DataTypesPrimitive DataTypes
How Computing Works?How Computing Works?
 Computers are machines that process dataComputers are machines that process data
 Data is stored in the computer memory inData is stored in the computer memory in
variablesvariables
 Variables haveVariables have namename,, data typedata type andand valuevalue
 Example of variable definition and assignmentExample of variable definition and assignment
in C#in C#
int count = 5;int count = 5;
Data typeData type
Variable nameVariable name
Variable valueVariable value
4
What Is a Data Type?What Is a Data Type?
 AA data typedata type::
Is a domain of values of similar characteristicsIs a domain of values of similar characteristics
Defines the type of information stored in theDefines the type of information stored in the
computer memory (in a variable)computer memory (in a variable)
 Examples:Examples:
Positive integers:Positive integers: 11,, 22,, 33,, ……
Alphabetical characters:Alphabetical characters: aa,, bb,, cc,, ……
Days of week:Days of week: MondayMonday,, TuesdayTuesday,, ……
5
Data Type CharacteristicsData Type Characteristics
 A data type has:A data type has:
Name (C# keyword or .NET type)Name (C# keyword or .NET type)
Size (how much memory is used)Size (how much memory is used)
Default valueDefault value
 Example:Example:
Integer numbers in C#Integer numbers in C#
Name:Name: intint
Size: 32 bits (4 bytes)Size: 32 bits (4 bytes)
Default value: 0Default value: 0
6
IntegerTypesIntegerTypes
What are Integer Types?What are Integer Types?
 Integer types:Integer types:
Represent whole numbersRepresent whole numbers
May be signed or unsignedMay be signed or unsigned
Have range of values, depending on the size ofHave range of values, depending on the size of
memory usedmemory used
 The default value of integer types is:The default value of integer types is:
00 – for integer types, except– for integer types, except
0L0L – for the– for the longlong typetype
8
Integer TypesInteger Types
 Integer types are:Integer types are:
sbytesbyte (-128 to 127): signed 8-bit(-128 to 127): signed 8-bit
bytebyte (0 to 255): unsigned 8-bit(0 to 255): unsigned 8-bit
shortshort (-32,768 to 32,767): signed 16-bit(-32,768 to 32,767): signed 16-bit
ushortushort (0 to 65,535): unsigned 16-bit(0 to 65,535): unsigned 16-bit
intint (-2,147,483,648 to 2,147,483,647): signed(-2,147,483,648 to 2,147,483,647): signed
32-bit32-bit
uintuint (0 to 4,294,967,295): unsigned 32-bit(0 to 4,294,967,295): unsigned 32-bit
9
Integer Types (2)Integer Types (2)
 More integer types:More integer types:
longlong (-9,223,372,036,854,775,808 to(-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807): signed 64-bit9,223,372,036,854,775,807): signed 64-bit
ulongulong (0 to 18,446,744,073,709,551,615):(0 to 18,446,744,073,709,551,615):
unsigned 64-bitunsigned 64-bit
10
Measuring Time – ExampleMeasuring Time – Example
 Depending on the unit of measure we may useDepending on the unit of measure we may use
different data types:different data types:
byte centuries = 20; // Usually a small numberbyte centuries = 20; // Usually a small number
ushort years = 2000;ushort years = 2000;
uint days = 730480;uint days = 730480;
ulong hours = 17531520; // May be a very big numberulong hours = 17531520; // May be a very big number
Console.WriteLine("{0} centuries is {1} years, orConsole.WriteLine("{0} centuries is {1} years, or
{2} days, or {3} hours.", centuries, years, days,{2} days, or {3} hours.", centuries, years, days,
hours);hours);
11
IntegerTypesIntegerTypes
Live DemoLive Demo
Floating-Point and DecimalFloating-Point and Decimal
Floating-PointTypesFloating-PointTypes
What are Floating-Point Types?What are Floating-Point Types?
 Floating-point types:Floating-point types:
Represent real numbersRepresent real numbers
May be signed or unsignedMay be signed or unsigned
Have range of values and different precisionHave range of values and different precision
depending on the used memorydepending on the used memory
Can behave abnormally in the calculationsCan behave abnormally in the calculations
14
Floating-Point TypesFloating-Point Types
 Floating-point types are:Floating-point types are:
floatfloat (±1.5 × 10(±1.5 × 10−45−45
to ±3.4 × 10to ±3.4 × 103838
): 32-bits,): 32-bits,
precision of 7 digitsprecision of 7 digits
doubledouble (±5.0 × 10(±5.0 × 10−324−324
to ±1.7 × 10to ±1.7 × 10308308
): 64-bits,): 64-bits,
precision of 15-16 digitsprecision of 15-16 digits
 The default value of floating-point types:The default value of floating-point types:
IsIs 0.0F0.0F for thefor the floatfloat typetype
IsIs 0.0D0.0D for thefor the doubledouble typetype
15
PI Precision – ExamplePI Precision – Example
 See below the difference in precision when usingSee below the difference in precision when using
floatfloat andand doubledouble::
 NOTE: The “NOTE: The “ff” suffix in the first statement!” suffix in the first statement!
 Real numbers are by default interpreted asReal numbers are by default interpreted as doubledouble!!
 One shouldOne should explicitlyexplicitly convert them toconvert them to floatfloat
float floatPI = 3.141592653589793238f;float floatPI = 3.141592653589793238f;
double doublePI = 3.141592653589793238;double doublePI = 3.141592653589793238;
Console.WriteLine("Float PI is: {0}", floatPI);Console.WriteLine("Float PI is: {0}", floatPI);
Console.WriteLine("Double PI is: {0}", doublePI);Console.WriteLine("Double PI is: {0}", doublePI);
16
Abnormalities in theAbnormalities in the
Floating-Point CalculationsFloating-Point Calculations
 Sometimes abnormalities can be observedSometimes abnormalities can be observed
when using floating-point numberswhen using floating-point numbers
Comparing floating-point numbers can not beComparing floating-point numbers can not be
performed directly with theperformed directly with the ==== operatoroperator
 Example:Example:
double a = 1.0f;double a = 1.0f;
double b = 0.33f;double b = 0.33f;
double sum = 1.33f;double sum = 1.33f;
bool equal = (a+b == sum); // False!!!bool equal = (a+b == sum); // False!!!
Console.WriteLine("a+b={0} sum={1} equal={2}",Console.WriteLine("a+b={0} sum={1} equal={2}",
a+b, sum, equal);a+b, sum, equal);
17
Decimal Floating-Point TypesDecimal Floating-Point Types
 There is a special decimal floating-pointThere is a special decimal floating-point
real number type in C#:real number type in C#:
decimaldecimal (±1,0 × 10(±1,0 × 10-28-28
to ±7,9 × 10to ±7,9 × 102828
): 128-bits,): 128-bits,
precision of 28-29 digitsprecision of 28-29 digits
Used for financial calculationsUsed for financial calculations
No round-off errorsNo round-off errors
Almost no loss of precisionAlmost no loss of precision
 The default value ofThe default value of decimaldecimal type is:type is:
0.00.0MM ((MM is the suffix for decimal numbers)is the suffix for decimal numbers)
18
Floating-Point and DecimalFloating-Point and Decimal
Floating-PointTypesFloating-PointTypes
Live DemoLive Demo
BooleanTypeBooleanType
The Boolean Data TypeThe Boolean Data Type
 TheThe Boolean data typeBoolean data type::
Is declared by theIs declared by the boolbool keywordkeyword
Has two possible values:Has two possible values: truetrue andand falsefalse
Is useful in logical expressionsIs useful in logical expressions
 The default value isThe default value is falsefalse
21
Boolean Values – ExampleBoolean Values – Example
 Example of boolean variables taking values ofExample of boolean variables taking values of
truetrue oror falsefalse::
int a = 1;int a = 1;
int b = 2;int b = 2;
bool greaterAB = (a > b);bool greaterAB = (a > b);
Console.WriteLine(greaterAB); // FalseConsole.WriteLine(greaterAB); // False
bool equalA1 = (a == 1);bool equalA1 = (a == 1);
Console.WriteLine(equalA1); // TrueConsole.WriteLine(equalA1); // True
22
BooleanTypeBooleanType
Live DemoLive Demo
CharacterTypeCharacterType
The Character Data TypeThe Character Data Type
 TheThe character data typecharacter data type::
Represents symbolic informationRepresents symbolic information
Is declared by theIs declared by the charchar keywordkeyword
Gives each symbol a corresponding integer codeGives each symbol a corresponding integer code
Has aHas a '0''0' default valuedefault value
Takes 16 bits of memory (fromTakes 16 bits of memory (from U+0000U+0000 toto
U+FFFFU+FFFF))
25
Characters and CodesCharacters and Codes
 The example below shows that every symbolThe example below shows that every symbol
has an its unique Unicode code:has an its unique Unicode code:
char symbol = 'a';char symbol = 'a';
Console.WriteLine("The code of '{0}' is: {1}",Console.WriteLine("The code of '{0}' is: {1}",
symbol, (int) symbol);symbol, (int) symbol);
symbol = 'b';symbol = 'b';
Console.WriteLine("The code of '{0}' is: {1}",Console.WriteLine("The code of '{0}' is: {1}",
symbol, (int) symbol);symbol, (int) symbol);
symbol = 'A';symbol = 'A';
Console.WriteLine("The code of '{0}' is: {1}",Console.WriteLine("The code of '{0}' is: {1}",
symbol, (int) symbol);symbol, (int) symbol);
26
CharacterTypeCharacterType
Live DemoLive Demo
StringTypeStringType
The String Data TypeThe String Data Type
 TheThe string data typestring data type::
Represents a sequence of charactersRepresents a sequence of characters
Is declared by theIs declared by the stringstring keywordkeyword
Has a default valueHas a default value nullnull (no value)(no value)
 Strings are enclosed in quotes:Strings are enclosed in quotes:
 Strings can be concatenatedStrings can be concatenated
Using theUsing the ++ operatoroperator
string s = "Microsoft .NET Framework";string s = "Microsoft .NET Framework";
29
Saying Hello – ExampleSaying Hello – Example
 Concatenating the two names of a person toConcatenating the two names of a person to
obtain his full name:obtain his full name:
NOTE: a space is missing between the twoNOTE: a space is missing between the two
names! We have to add it manuallynames! We have to add it manually
string firstName = "Ivan";string firstName = "Ivan";
string lastName = "Ivanov";string lastName = "Ivanov";
Console.WriteLine("Hello, {0}!n", firstName);Console.WriteLine("Hello, {0}!n", firstName);
string fullName = firstName + " " + lastName;string fullName = firstName + " " + lastName;
Console.WriteLine("Your full name is {0}.",Console.WriteLine("Your full name is {0}.",
fullName);fullName);
30
StringTypeStringType
Live DemoLive Demo
ObjectTypeObjectType
The Object TypeThe Object Type
 The object type:The object type:
Is declared by theIs declared by the objectobject keywordkeyword
Is the base type of all other typesIs the base type of all other types
Can hold values of any typeCan hold values of any type
33
Using ObjectsUsing Objects
 Example of an object variable taking differentExample of an object variable taking different
types of data:types of data:
object dataContainer = 5;object dataContainer = 5;
Console.Write("The value of dataContainer is: ");Console.Write("The value of dataContainer is: ");
Console.WriteLine(dataContainer);Console.WriteLine(dataContainer);
dataContainer = "Five";dataContainer = "Five";
Console.Write("The value of dataContainer is: ");Console.Write("The value of dataContainer is: ");
Console.WriteLine(dataContainer);Console.WriteLine(dataContainer);
34
ObjectsObjects
Live DemoLive Demo
IntroducingVariablesIntroducingVariables
pp qq
ii
What Is a Variable?What Is a Variable?
 A variable is a:A variable is a:
Placeholder of information that can usually bePlaceholder of information that can usually be
changed at run-timechanged at run-time
 Variables allow you to:Variables allow you to:
Store informationStore information
Retrieve the stored informationRetrieve the stored information
Manipulate the stored informationManipulate the stored information
37
Variable CharacteristicsVariable Characteristics
 A variable has:A variable has:
NameName
Type (of stored data)Type (of stored data)
ValueValue
 Example:Example:
Name:Name: countercounter
Type:Type: intint
Value:Value: 55
int counter = 5;int counter = 5;
38
Declaring And UsingDeclaring And Using
VariablesVariables
Declaring VariablesDeclaring Variables
 When declaring a variable we:When declaring a variable we:
Specify its typeSpecify its type
Specify its name (called identifier)Specify its name (called identifier)
May give it an initial valueMay give it an initial value
 The syntax is the following:The syntax is the following:
 Example:Example:
<data_type> <identifier> [= <initialization>];<data_type> <identifier> [= <initialization>];
int height = 200;int height = 200;
40
IdentifiersIdentifiers
 Identifiers may consist of:Identifiers may consist of:
Letters (Unicode)Letters (Unicode)
Digits [0-9]Digits [0-9]
Underscore "_"Underscore "_"
 IdentifiersIdentifiers
Can begin only with a letter or an underscoreCan begin only with a letter or an underscore
Cannot be a C# keywordCannot be a C# keyword
41
Identifiers (2)Identifiers (2)
 IdentifiersIdentifiers
Should have a descriptive nameShould have a descriptive name
It is recommended to use only Latin lettersIt is recommended to use only Latin letters
Should be neither too long nor too shortShould be neither too long nor too short
 Note:Note:
In C# small letters are considered different thanIn C# small letters are considered different than
the capital letters (case sensitivity)the capital letters (case sensitivity)
42
Identifiers – ExamplesIdentifiers – Examples
 Examples of correct identifiers:Examples of correct identifiers:
 Examples of incorrect identifiers:Examples of incorrect identifiers:
int new;int new; // new is a keyword// new is a keyword
int 2Pac;int 2Pac; // Cannot begin with a digit// Cannot begin with a digit
int New = 2; // Here N is capitalint New = 2; // Here N is capital
int _2Pac; // This identifiers begins with _int _2Pac; // This identifiers begins with _
string поздрав = "Hello"; // Unicode symbols usedstring поздрав = "Hello"; // Unicode symbols used
// The following is more appropriate:// The following is more appropriate:
string greeting = "Hello";string greeting = "Hello";
int n = 100; // Undescriptiveint n = 100; // Undescriptive
int numberOfClients = 100; // Descriptiveint numberOfClients = 100; // Descriptive
// Overdescriptive identifier:// Overdescriptive identifier:
int numberOfPrivateClientOfTheFirm = 100;int numberOfPrivateClientOfTheFirm = 100;
43
AssigningValuesAssigningValues
ToVariablesToVariables
Assigning ValuesAssigning Values
 Assigning of values to variablesAssigning of values to variables
Is achieved by theIs achieved by the == operatoroperator
 TheThe == operator hasoperator has
Variable identifier on the leftVariable identifier on the left
Value of the corresponding data type on theValue of the corresponding data type on the
rightright
Could be used in a cascade calling, whereCould be used in a cascade calling, where
assigning is done from right to leftassigning is done from right to left
45
Assigning Values – ExamplesAssigning Values – Examples
 Assigning values example:Assigning values example:
int firstValue = 5;int firstValue = 5;
int secondValue;int secondValue;
int thirdValue;int thirdValue;
// Using an already declared variable:// Using an already declared variable:
secondValue = firstValue;secondValue = firstValue;
// The following cascade calling assigns// The following cascade calling assigns
// 3 to firstValue and then firstValue// 3 to firstValue and then firstValue
// to thirdValue, so both variables have// to thirdValue, so both variables have
// the value 3 as a result:// the value 3 as a result:
thirdValue = firstValue = 3; // Avoid this!thirdValue = firstValue = 3; // Avoid this!
46
Initializing VariablesInitializing Variables
 InitializingInitializing
Is assigning of initial valueIs assigning of initial value
Must be done before the variable is used!Must be done before the variable is used!
 Several ways of initializing:Several ways of initializing:
By using theBy using the newnew keywordkeyword
By using a literal expressionBy using a literal expression
By referring to an already initialized variableBy referring to an already initialized variable
47
Initialization – ExamplesInitialization – Examples
 Example of some initializations:Example of some initializations:
// The following would assign the default// The following would assign the default
// value of the int type to num:// value of the int type to num:
int num = new int(); // num = 0int num = new int(); // num = 0
// This is how we use a literal expression:// This is how we use a literal expression:
float heightInMeters = 1.74f;float heightInMeters = 1.74f;
// Here we use an already initialized variable:// Here we use an already initialized variable:
string greeting = "Hello World!";string greeting = "Hello World!";
string message = greeting;string message = greeting;
48
Assigning andAssigning and
InitializingVariablesInitializingVariables
Live DemoLive Demo
LiteralsLiterals
What are Literals?What are Literals?
 Literals are:Literals are:
Representations of values in the source codeRepresentations of values in the source code
 There are six types of literalsThere are six types of literals
BooleanBoolean
IntegerInteger
RealReal
CharacterCharacter
StringString
TheThe nullnull literalliteral
51
Boolean and Integer LiteralsBoolean and Integer Literals
 The boolean literals are:The boolean literals are:
truetrue
falsefalse
 The integer literals:The integer literals:
Are used for variables of typeAre used for variables of type intint,, uintuint,, longlong,,
andand ulongulong
Consist of digitsConsist of digits
May have a sign (May have a sign (++,,--))
May be in a hexadecimal formatMay be in a hexadecimal format
52
Integer LiteralsInteger Literals
 Examples of integer literalsExamples of integer literals
TheThe ''0x0x'' andand ''0X0X'' prefixes mean aprefixes mean a
hexadecimal value, e.g.hexadecimal value, e.g. 0xA8F10xA8F1
TheThe ''uu'' andand ''UU'' suffixes mean asuffixes mean a ulongulong oror uintuint
type, e.g.type, e.g. 12345678U12345678U
TheThe ''ll'' andand ''LL'' suffixes mean asuffixes mean a longlong oror ulongulong
type, e.g.type, e.g. 9876543L9876543L
53
Integer Literals – ExampleInteger Literals – Example
 Note: the letter ‘Note: the letter ‘ll’ is easily confused with the’ is easily confused with the
digit ‘digit ‘11’ so it’s better to use ‘’ so it’s better to use ‘LL’!!!’!!!
// The following variables are// The following variables are
// initialized with the same value:// initialized with the same value:
int numberInHex = -0x10;int numberInHex = -0x10;
int numberInDec = -16;int numberInDec = -16;
// The following causes an error,// The following causes an error,
because 234u is of type uintbecause 234u is of type uint
int unsignedInt = 234u;int unsignedInt = 234u;
// The following causes an error,// The following causes an error,
because 234L is of type longbecause 234L is of type long
int longInt = 234L;int longInt = 234L;
54
Real LiteralsReal Literals
 The real literals:The real literals:
Are used for values of typeAre used for values of type floatfloat,, doubledouble andand
decimaldecimal
May consist of digits, a sign and “May consist of digits, a sign and “..””
May be in exponential notation:May be in exponential notation: 6.02e+236.02e+23
 The “The “ff” and “” and “FF” suffixes mean” suffixes mean floatfloat
 The “The “dd” and “” and “DD” suffixes mean” suffixes mean doubledouble
 The “The “mm” and “” and “MM” suffixes mean” suffixes mean decimaldecimal
 The default interpretation isThe default interpretation is doubledouble
55
Real Literals – ExampleReal Literals – Example
 Example of incorrectExample of incorrect floatfloat literal:literal:
 A correct way to assign floating-point valueA correct way to assign floating-point value
(using also the exponential format):(using also the exponential format):
56
// The following causes an error// The following causes an error
// because 12.5 is double by default// because 12.5 is double by default
float realNumber = 12.5;float realNumber = 12.5;
// The following is the correct// The following is the correct
// way of assigning the value:// way of assigning the value:
float realNumber = 12.5f;float realNumber = 12.5f;
// This is the same value in exponential format:// This is the same value in exponential format:
realNumber = 1.25e+7f;realNumber = 1.25e+7f;
Character LiteralsCharacter Literals
 The character literals:The character literals:
Are used for values of theAre used for values of the charchar typetype
Consist of two single quotes surrounding theConsist of two single quotes surrounding the
character value:character value: ''<value><value>''
 The value may be:The value may be:
SymbolSymbol
The code of the symbolThe code of the symbol
Escaping sequenceEscaping sequence
57
Escaping SequencesEscaping Sequences
 Escaping sequences are:Escaping sequences are:
Means of presenting a symbol that is usuallyMeans of presenting a symbol that is usually
interpreted otherwise (likeinterpreted otherwise (like ''))
Means of presenting system symbols (like theMeans of presenting system symbols (like the
new line symbol)new line symbol)
 Common escaping sequences are:Common escaping sequences are:
 '' for single quotefor single quote "" for double quotefor double quote
  for backslashfor backslash nn for new linefor new line
 uXXXXuXXXX for denoting any other Unicode symbolfor denoting any other Unicode symbol
58
Character Literals – ExampleCharacter Literals – Example
 Examples of different character literals:Examples of different character literals:
char symbol = 'a'; // An ordinary symbolchar symbol = 'a'; // An ordinary symbol
symbol = 'u006F'; // Unicode symbol code insymbol = 'u006F'; // Unicode symbol code in
// a hexadecimal format// a hexadecimal format
symbol = 'u8449'; //symbol = 'u8449'; // 葉葉 ((Leaf in Traditional Chinese)Leaf in Traditional Chinese)
symbol = '''; // Assigning the single quote symbolsymbol = '''; // Assigning the single quote symbol
symbol = ''; // Assigning the backslash symbolsymbol = ''; // Assigning the backslash symbol
symbol = 'n'; // Assigning new line symbolsymbol = 'n'; // Assigning new line symbol
symbol = 't'; // Assigning TAB symbolsymbol = 't'; // Assigning TAB symbol
symbol = "a"; // Incorrect: use single quotessymbol = "a"; // Incorrect: use single quotes
59
String LiteralsString Literals
 String literals:String literals:
Are used for values of the string typeAre used for values of the string type
Consist of two double quotes surrounding theConsist of two double quotes surrounding the
value:value: ""<value><value>""
May have aMay have a @@ prefix which ignores the usedprefix which ignores the used
escaping sequences:escaping sequences: @@"<value>""<value>"
 The value is a sequence of character literalsThe value is a sequence of character literals
string s = "I am a sting literal";string s = "I am a sting literal";
60
String Literals – ExampleString Literals – Example
 Benefits of quoted strings (theBenefits of quoted strings (the @@ prefix):prefix):
 In quoted stringsIn quoted strings "" is used instead ofis used instead of """"!!
// Here is a string literal using escape sequences// Here is a string literal using escape sequences
string quotation = ""Hello, Jude", he said.";string quotation = ""Hello, Jude", he said.";
string path = "C:WINNTDartsDarts.exe";string path = "C:WINNTDartsDarts.exe";
// Here is an example of the usage of @// Here is an example of the usage of @
quotation = @"""Hello, Jimmy!"", she answered.";quotation = @"""Hello, Jimmy!"", she answered.";
path = @"C:WINNTDartsDarts.exe";path = @"C:WINNTDartsDarts.exe";
string str = @"somestring str = @"some
text";text";
61
String LiteralsString Literals
Live DemoLive Demo
NullableTypesNullableTypes
63
Nullable TypesNullable Types
 NullableNullable types are instances of thetypes are instances of the
System.NullableSystem.Nullable structstruct
Wrapper over theWrapper over the primitiveprimitive typestypes
E.g.E.g. int?int?,, double?double?, etc., etc.
 NullabeNullabe type can represent the normal rangetype can represent the normal range
of values for its underlying value type, plus anof values for its underlying value type, plus an
additionaladditional nullnull valuevalue
 Useful when dealing withUseful when dealing with DatabasesDatabases or otheror other
structures that have default valuestructures that have default value nullnull
Nullable Types – ExampleNullable Types – Example
int? someInteger = null;int? someInteger = null;
Console.WriteLine(Console.WriteLine(
"This is the integer with Null value -> " + someInteger);"This is the integer with Null value -> " + someInteger);
someInteger = 5;someInteger = 5;
Console.WriteLine(Console.WriteLine(
"This is the integer with value 5 -> " + someInteger);"This is the integer with value 5 -> " + someInteger);
double? someDouble = null;double? someDouble = null;
Console.WriteLine(Console.WriteLine(
"This is the real number with Null value -> ""This is the real number with Null value -> "
+ someDouble);+ someDouble);
someDouble = 2.5;someDouble = 2.5;
Console.WriteLine(Console.WriteLine(
"This is the real number with value 5 -> " +"This is the real number with value 5 -> " +
someDouble);someDouble);
Example withExample with IntegerInteger::
Example withExample with DoubleDouble::
NullableTypesNullableTypes
Live DemoLive Demo
66
Questions?Questions?
Primitive DataPrimitive Data
Types andVariablesTypes andVariables
http://academy.telerik.com
ExercisesExercises
1.1. Declare five variables choosing for each of them theDeclare five variables choosing for each of them the
most appropriate of the typesmost appropriate of the types bytebyte,, sbytesbyte,, shortshort,,
ushortushort,, intint,, uintuint,, longlong,, ulongulong to represent theto represent the
following values: 52130, -115, 4825932, 97, -10000.following values: 52130, -115, 4825932, 97, -10000.
2.2. Which of the following values can be assigned to aWhich of the following values can be assigned to a
variable of typevariable of type floatfloat and which to a variable ofand which to a variable of
typetype doubledouble: 34.567839023, 12.345, 8923.1234857,: 34.567839023, 12.345, 8923.1234857,
3456.091?3456.091?
3.3. Write a program that safely compares floating-pointWrite a program that safely compares floating-point
numbers with precision ofnumbers with precision of 0.0000010.000001..
68
Exercises (2)Exercises (2)
4.4. Declare an integer variable and assign it with theDeclare an integer variable and assign it with the
value 254 in hexadecimal format. Use Windowsvalue 254 in hexadecimal format. Use Windows
Calculator to find its hexadecimal representation.Calculator to find its hexadecimal representation.
5.5. Declare a character variable and assign it with theDeclare a character variable and assign it with the
symbol that has Unicode code 72. Hint: first use thesymbol that has Unicode code 72. Hint: first use the
Windows Calculator to find the hexadecimalWindows Calculator to find the hexadecimal
representation of 72.representation of 72.
6.6. Declare a boolean variable calledDeclare a boolean variable called isFemaleisFemale andand
assign an appropriate value corresponding to yourassign an appropriate value corresponding to your
gender.gender.
69
Exercises (3)Exercises (3)
7.7. Declare twoDeclare two stringstring variables and assign them withvariables and assign them with
“Hello” and “World”. Declare an“Hello” and “World”. Declare an objectobject variable andvariable and
assign it with the concatenation of the first twoassign it with the concatenation of the first two
variables (mind adding an interval). Declare a thirdvariables (mind adding an interval). Declare a third
stringstring variable and initialize it with the value of thevariable and initialize it with the value of the
object variable (you should perform type casting).object variable (you should perform type casting).
8.8. Declare twoDeclare two stringstring variables and assign them withvariables and assign them with
following value:following value:
Do the above in two different ways: with and withoutDo the above in two different ways: with and without
using quoted strings.using quoted strings.
The "use" of quotations causes difficulties.The "use" of quotations causes difficulties.
70
Exercises (4)Exercises (4)
9.9. Write a program thatWrite a program that prints an isosceles triangle ofprints an isosceles triangle of
9 copyright symbols9 copyright symbols ©©. Use Windows Character. Use Windows Character
Map to find the Unicode code of theMap to find the Unicode code of the ©© symbol.symbol.
10.10. A marketing firm wants to keep record of itsA marketing firm wants to keep record of its
employees. Each record would have the followingemployees. Each record would have the following
characteristics – first name, family name,characteristics – first name, family name, age,age,
gender (m or f), ID number,gender (m or f), ID number, unique employeeunique employee
number (27560000 to 27569999). Declare thenumber (27560000 to 27569999). Declare the
variables needed to keep the information for avariables needed to keep the information for a
single employee using appropriate data typessingle employee using appropriate data types andand
descriptive names.descriptive names.
11.11. Declare two integer variables and assign them withDeclare two integer variables and assign them with
5 and 10 and after that exchange their values.5 and 10 and after that exchange their values.
71

Weitere ähnliche Inhalte

Was ist angesagt?

Introducción a Sql
Introducción a SqlIntroducción a Sql
Introducción a Sqlalexmerono
 
1.1 core programming [understand computer storage and data types]
1.1 core programming [understand computer storage and data types]1.1 core programming [understand computer storage and data types]
1.1 core programming [understand computer storage and data types]tototo147
 
Database Programming
Database ProgrammingDatabase Programming
Database ProgrammingHenry Osborne
 
DBMS languages/ Types of SQL Commands
DBMS languages/ Types of SQL CommandsDBMS languages/ Types of SQL Commands
DBMS languages/ Types of SQL CommandsBHARATH KUMAR
 
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 2MOHIT TOMAR
 
User defined data type
User defined data typeUser defined data type
User defined data typeAmit Kapoor
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL CommandsShrija Madhu
 
LINUX:Control statements in shell programming
LINUX:Control statements in shell programmingLINUX:Control statements in shell programming
LINUX:Control statements in shell programmingbhatvijetha
 
JSON and the Oracle Database
JSON and the Oracle DatabaseJSON and the Oracle Database
JSON and the Oracle DatabaseMaria Colgan
 
A short introduction to database systems.ppt
A short introduction to  database systems.pptA short introduction to  database systems.ppt
A short introduction to database systems.pptMuruly Krishan
 
directory structure and file system mounting
directory structure and file system mountingdirectory structure and file system mounting
directory structure and file system mountingrajshreemuthiah
 

Was ist angesagt? (20)

Introducción a Sql
Introducción a SqlIntroducción a Sql
Introducción a Sql
 
1.1 core programming [understand computer storage and data types]
1.1 core programming [understand computer storage and data types]1.1 core programming [understand computer storage and data types]
1.1 core programming [understand computer storage and data types]
 
Database Programming
Database ProgrammingDatabase Programming
Database Programming
 
DBMS languages/ Types of SQL Commands
DBMS languages/ Types of SQL CommandsDBMS languages/ Types of SQL Commands
DBMS languages/ Types of SQL Commands
 
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
 
D B M S Animate
D B M S AnimateD B M S Animate
D B M S Animate
 
Character set of c
Character set of cCharacter set of c
Character set of c
 
User defined data type
User defined data typeUser defined data type
User defined data type
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
File handling-c
File handling-cFile handling-c
File handling-c
 
Data Abstraction
Data AbstractionData Abstraction
Data Abstraction
 
Basic SQL and History
 Basic SQL and History Basic SQL and History
Basic SQL and History
 
LINUX:Control statements in shell programming
LINUX:Control statements in shell programmingLINUX:Control statements in shell programming
LINUX:Control statements in shell programming
 
C++
C++C++
C++
 
Typedef
TypedefTypedef
Typedef
 
JSON and the Oracle Database
JSON and the Oracle DatabaseJSON and the Oracle Database
JSON and the Oracle Database
 
A short introduction to database systems.ppt
A short introduction to  database systems.pptA short introduction to  database systems.ppt
A short introduction to database systems.ppt
 
directory structure and file system mounting
directory structure and file system mountingdirectory structure and file system mounting
directory structure and file system mounting
 
Data integrity
Data integrityData integrity
Data integrity
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 

Ähnlich wie Primitive Data Types and Variables Lesson 02

02 Primitive data types and variables
02 Primitive data types and variables02 Primitive data types and variables
02 Primitive data types and variablesmaznabili
 
C# Language Overview Part I
C# Language Overview Part IC# Language Overview Part I
C# Language Overview Part IDoncho Minkov
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and VariablesIntro C# Book
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1Hossein Zahed
 
02. Data Type and Variables
02. Data Type and Variables02. Data Type and Variables
02. Data Type and VariablesTommy Vercety
 
Literals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiersLiterals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiersTanishq Soni
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 
C C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.inC C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.inTIB Academy
 
5-Lec - Datatypes.ppt
5-Lec - Datatypes.ppt5-Lec - Datatypes.ppt
5-Lec - Datatypes.pptAqeelAbbas94
 
Introduction to Basics of Python
Introduction to Basics of PythonIntroduction to Basics of Python
Introduction to Basics of PythonElewayte
 
Data Type is a basic classification which identifies.docx
Data Type is a basic classification which identifies.docxData Type is a basic classification which identifies.docx
Data Type is a basic classification which identifies.docxtheodorelove43763
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_castsAbed Bukhari
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxKrishanPalSingh39
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 

Ähnlich wie Primitive Data Types and Variables Lesson 02 (20)

02 Primitive data types and variables
02 Primitive data types and variables02 Primitive data types and variables
02 Primitive data types and variables
 
C# Language Overview Part I
C# Language Overview Part IC# Language Overview Part I
C# Language Overview Part I
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1
 
C# overview part 1
C# overview part 1C# overview part 1
C# overview part 1
 
02. Data Type and Variables
02. Data Type and Variables02. Data Type and Variables
02. Data Type and Variables
 
Literals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiersLiterals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiers
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
C C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.inC C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.in
 
Lecture03
Lecture03Lecture03
Lecture03
 
5-Lec - Datatypes.ppt
5-Lec - Datatypes.ppt5-Lec - Datatypes.ppt
5-Lec - Datatypes.ppt
 
Introduction to Basics of Python
Introduction to Basics of PythonIntroduction to Basics of Python
Introduction to Basics of Python
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Data Type is a basic classification which identifies.docx
Data Type is a basic classification which identifies.docxData Type is a basic classification which identifies.docx
Data Type is a basic classification which identifies.docx
 
C tutorial
C tutorialC tutorial
C tutorial
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
python-ch2.pptx
python-ch2.pptxpython-ch2.pptx
python-ch2.pptx
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptx
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 

Mehr von A-Tech and Software Development (13)

Online Bus Reservation System
Online Bus Reservation SystemOnline Bus Reservation System
Online Bus Reservation System
 
Introduction to Programming Lesson 01
Introduction to Programming Lesson 01Introduction to Programming Lesson 01
Introduction to Programming Lesson 01
 
Stacks, Queues, Deques
Stacks, Queues, DequesStacks, Queues, Deques
Stacks, Queues, Deques
 
Survey Of Software Houses
Survey Of Software HousesSurvey Of Software Houses
Survey Of Software Houses
 
Traffic signal's
Traffic signal'sTraffic signal's
Traffic signal's
 
Canteen Store Department
Canteen Store DepartmentCanteen Store Department
Canteen Store Department
 
Chick development
Chick developmentChick development
Chick development
 
Peripheral devices
Peripheral devicesPeripheral devices
Peripheral devices
 
Bank System
Bank SystemBank System
Bank System
 
Bank System
Bank SystemBank System
Bank System
 
Bank Management System
Bank Management SystemBank Management System
Bank Management System
 
Village Life Of Pakistan
Village Life Of PakistanVillage Life Of Pakistan
Village Life Of Pakistan
 
Role of media in our society
Role of media in our societyRole of media in our society
Role of media in our society
 

Kürzlich hochgeladen

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 

Kürzlich hochgeladen (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 

Primitive Data Types and Variables Lesson 02

  • 1. Primitive DataPrimitive Data Types andVariablesTypes andVariables Creating and RunningYour First C# ProgramCreating and RunningYour First C# Program Arshman SaleemArshman Saleem A Tech & Software DevelopmentA Tech & Software Development
  • 2. Table of ContentsTable of Contents 1.1. Primitive Data TypesPrimitive Data Types  IntegerInteger  Floating-Point / Decimal Floating-PointFloating-Point / Decimal Floating-Point  BooleanBoolean  CharacterCharacter  StringString  ObjectObject 1.1. Declaring and Using VariablesDeclaring and Using Variables  IdentifiersIdentifiers  Declaring Variables and Assigning ValuesDeclaring Variables and Assigning Values  LiteralsLiterals 1.1. NullableNullable typestypes 2
  • 4. How Computing Works?How Computing Works?  Computers are machines that process dataComputers are machines that process data  Data is stored in the computer memory inData is stored in the computer memory in variablesvariables  Variables haveVariables have namename,, data typedata type andand valuevalue  Example of variable definition and assignmentExample of variable definition and assignment in C#in C# int count = 5;int count = 5; Data typeData type Variable nameVariable name Variable valueVariable value 4
  • 5. What Is a Data Type?What Is a Data Type?  AA data typedata type:: Is a domain of values of similar characteristicsIs a domain of values of similar characteristics Defines the type of information stored in theDefines the type of information stored in the computer memory (in a variable)computer memory (in a variable)  Examples:Examples: Positive integers:Positive integers: 11,, 22,, 33,, …… Alphabetical characters:Alphabetical characters: aa,, bb,, cc,, …… Days of week:Days of week: MondayMonday,, TuesdayTuesday,, …… 5
  • 6. Data Type CharacteristicsData Type Characteristics  A data type has:A data type has: Name (C# keyword or .NET type)Name (C# keyword or .NET type) Size (how much memory is used)Size (how much memory is used) Default valueDefault value  Example:Example: Integer numbers in C#Integer numbers in C# Name:Name: intint Size: 32 bits (4 bytes)Size: 32 bits (4 bytes) Default value: 0Default value: 0 6
  • 8. What are Integer Types?What are Integer Types?  Integer types:Integer types: Represent whole numbersRepresent whole numbers May be signed or unsignedMay be signed or unsigned Have range of values, depending on the size ofHave range of values, depending on the size of memory usedmemory used  The default value of integer types is:The default value of integer types is: 00 – for integer types, except– for integer types, except 0L0L – for the– for the longlong typetype 8
  • 9. Integer TypesInteger Types  Integer types are:Integer types are: sbytesbyte (-128 to 127): signed 8-bit(-128 to 127): signed 8-bit bytebyte (0 to 255): unsigned 8-bit(0 to 255): unsigned 8-bit shortshort (-32,768 to 32,767): signed 16-bit(-32,768 to 32,767): signed 16-bit ushortushort (0 to 65,535): unsigned 16-bit(0 to 65,535): unsigned 16-bit intint (-2,147,483,648 to 2,147,483,647): signed(-2,147,483,648 to 2,147,483,647): signed 32-bit32-bit uintuint (0 to 4,294,967,295): unsigned 32-bit(0 to 4,294,967,295): unsigned 32-bit 9
  • 10. Integer Types (2)Integer Types (2)  More integer types:More integer types: longlong (-9,223,372,036,854,775,808 to(-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807): signed 64-bit9,223,372,036,854,775,807): signed 64-bit ulongulong (0 to 18,446,744,073,709,551,615):(0 to 18,446,744,073,709,551,615): unsigned 64-bitunsigned 64-bit 10
  • 11. Measuring Time – ExampleMeasuring Time – Example  Depending on the unit of measure we may useDepending on the unit of measure we may use different data types:different data types: byte centuries = 20; // Usually a small numberbyte centuries = 20; // Usually a small number ushort years = 2000;ushort years = 2000; uint days = 730480;uint days = 730480; ulong hours = 17531520; // May be a very big numberulong hours = 17531520; // May be a very big number Console.WriteLine("{0} centuries is {1} years, orConsole.WriteLine("{0} centuries is {1} years, or {2} days, or {3} hours.", centuries, years, days,{2} days, or {3} hours.", centuries, years, days, hours);hours); 11
  • 13. Floating-Point and DecimalFloating-Point and Decimal Floating-PointTypesFloating-PointTypes
  • 14. What are Floating-Point Types?What are Floating-Point Types?  Floating-point types:Floating-point types: Represent real numbersRepresent real numbers May be signed or unsignedMay be signed or unsigned Have range of values and different precisionHave range of values and different precision depending on the used memorydepending on the used memory Can behave abnormally in the calculationsCan behave abnormally in the calculations 14
  • 15. Floating-Point TypesFloating-Point Types  Floating-point types are:Floating-point types are: floatfloat (±1.5 × 10(±1.5 × 10−45−45 to ±3.4 × 10to ±3.4 × 103838 ): 32-bits,): 32-bits, precision of 7 digitsprecision of 7 digits doubledouble (±5.0 × 10(±5.0 × 10−324−324 to ±1.7 × 10to ±1.7 × 10308308 ): 64-bits,): 64-bits, precision of 15-16 digitsprecision of 15-16 digits  The default value of floating-point types:The default value of floating-point types: IsIs 0.0F0.0F for thefor the floatfloat typetype IsIs 0.0D0.0D for thefor the doubledouble typetype 15
  • 16. PI Precision – ExamplePI Precision – Example  See below the difference in precision when usingSee below the difference in precision when using floatfloat andand doubledouble::  NOTE: The “NOTE: The “ff” suffix in the first statement!” suffix in the first statement!  Real numbers are by default interpreted asReal numbers are by default interpreted as doubledouble!!  One shouldOne should explicitlyexplicitly convert them toconvert them to floatfloat float floatPI = 3.141592653589793238f;float floatPI = 3.141592653589793238f; double doublePI = 3.141592653589793238;double doublePI = 3.141592653589793238; Console.WriteLine("Float PI is: {0}", floatPI);Console.WriteLine("Float PI is: {0}", floatPI); Console.WriteLine("Double PI is: {0}", doublePI);Console.WriteLine("Double PI is: {0}", doublePI); 16
  • 17. Abnormalities in theAbnormalities in the Floating-Point CalculationsFloating-Point Calculations  Sometimes abnormalities can be observedSometimes abnormalities can be observed when using floating-point numberswhen using floating-point numbers Comparing floating-point numbers can not beComparing floating-point numbers can not be performed directly with theperformed directly with the ==== operatoroperator  Example:Example: double a = 1.0f;double a = 1.0f; double b = 0.33f;double b = 0.33f; double sum = 1.33f;double sum = 1.33f; bool equal = (a+b == sum); // False!!!bool equal = (a+b == sum); // False!!! Console.WriteLine("a+b={0} sum={1} equal={2}",Console.WriteLine("a+b={0} sum={1} equal={2}", a+b, sum, equal);a+b, sum, equal); 17
  • 18. Decimal Floating-Point TypesDecimal Floating-Point Types  There is a special decimal floating-pointThere is a special decimal floating-point real number type in C#:real number type in C#: decimaldecimal (±1,0 × 10(±1,0 × 10-28-28 to ±7,9 × 10to ±7,9 × 102828 ): 128-bits,): 128-bits, precision of 28-29 digitsprecision of 28-29 digits Used for financial calculationsUsed for financial calculations No round-off errorsNo round-off errors Almost no loss of precisionAlmost no loss of precision  The default value ofThe default value of decimaldecimal type is:type is: 0.00.0MM ((MM is the suffix for decimal numbers)is the suffix for decimal numbers) 18
  • 19. Floating-Point and DecimalFloating-Point and Decimal Floating-PointTypesFloating-PointTypes Live DemoLive Demo
  • 21. The Boolean Data TypeThe Boolean Data Type  TheThe Boolean data typeBoolean data type:: Is declared by theIs declared by the boolbool keywordkeyword Has two possible values:Has two possible values: truetrue andand falsefalse Is useful in logical expressionsIs useful in logical expressions  The default value isThe default value is falsefalse 21
  • 22. Boolean Values – ExampleBoolean Values – Example  Example of boolean variables taking values ofExample of boolean variables taking values of truetrue oror falsefalse:: int a = 1;int a = 1; int b = 2;int b = 2; bool greaterAB = (a > b);bool greaterAB = (a > b); Console.WriteLine(greaterAB); // FalseConsole.WriteLine(greaterAB); // False bool equalA1 = (a == 1);bool equalA1 = (a == 1); Console.WriteLine(equalA1); // TrueConsole.WriteLine(equalA1); // True 22
  • 25. The Character Data TypeThe Character Data Type  TheThe character data typecharacter data type:: Represents symbolic informationRepresents symbolic information Is declared by theIs declared by the charchar keywordkeyword Gives each symbol a corresponding integer codeGives each symbol a corresponding integer code Has aHas a '0''0' default valuedefault value Takes 16 bits of memory (fromTakes 16 bits of memory (from U+0000U+0000 toto U+FFFFU+FFFF)) 25
  • 26. Characters and CodesCharacters and Codes  The example below shows that every symbolThe example below shows that every symbol has an its unique Unicode code:has an its unique Unicode code: char symbol = 'a';char symbol = 'a'; Console.WriteLine("The code of '{0}' is: {1}",Console.WriteLine("The code of '{0}' is: {1}", symbol, (int) symbol);symbol, (int) symbol); symbol = 'b';symbol = 'b'; Console.WriteLine("The code of '{0}' is: {1}",Console.WriteLine("The code of '{0}' is: {1}", symbol, (int) symbol);symbol, (int) symbol); symbol = 'A';symbol = 'A'; Console.WriteLine("The code of '{0}' is: {1}",Console.WriteLine("The code of '{0}' is: {1}", symbol, (int) symbol);symbol, (int) symbol); 26
  • 29. The String Data TypeThe String Data Type  TheThe string data typestring data type:: Represents a sequence of charactersRepresents a sequence of characters Is declared by theIs declared by the stringstring keywordkeyword Has a default valueHas a default value nullnull (no value)(no value)  Strings are enclosed in quotes:Strings are enclosed in quotes:  Strings can be concatenatedStrings can be concatenated Using theUsing the ++ operatoroperator string s = "Microsoft .NET Framework";string s = "Microsoft .NET Framework"; 29
  • 30. Saying Hello – ExampleSaying Hello – Example  Concatenating the two names of a person toConcatenating the two names of a person to obtain his full name:obtain his full name: NOTE: a space is missing between the twoNOTE: a space is missing between the two names! We have to add it manuallynames! We have to add it manually string firstName = "Ivan";string firstName = "Ivan"; string lastName = "Ivanov";string lastName = "Ivanov"; Console.WriteLine("Hello, {0}!n", firstName);Console.WriteLine("Hello, {0}!n", firstName); string fullName = firstName + " " + lastName;string fullName = firstName + " " + lastName; Console.WriteLine("Your full name is {0}.",Console.WriteLine("Your full name is {0}.", fullName);fullName); 30
  • 33. The Object TypeThe Object Type  The object type:The object type: Is declared by theIs declared by the objectobject keywordkeyword Is the base type of all other typesIs the base type of all other types Can hold values of any typeCan hold values of any type 33
  • 34. Using ObjectsUsing Objects  Example of an object variable taking differentExample of an object variable taking different types of data:types of data: object dataContainer = 5;object dataContainer = 5; Console.Write("The value of dataContainer is: ");Console.Write("The value of dataContainer is: "); Console.WriteLine(dataContainer);Console.WriteLine(dataContainer); dataContainer = "Five";dataContainer = "Five"; Console.Write("The value of dataContainer is: ");Console.Write("The value of dataContainer is: "); Console.WriteLine(dataContainer);Console.WriteLine(dataContainer); 34
  • 37. What Is a Variable?What Is a Variable?  A variable is a:A variable is a: Placeholder of information that can usually bePlaceholder of information that can usually be changed at run-timechanged at run-time  Variables allow you to:Variables allow you to: Store informationStore information Retrieve the stored informationRetrieve the stored information Manipulate the stored informationManipulate the stored information 37
  • 38. Variable CharacteristicsVariable Characteristics  A variable has:A variable has: NameName Type (of stored data)Type (of stored data) ValueValue  Example:Example: Name:Name: countercounter Type:Type: intint Value:Value: 55 int counter = 5;int counter = 5; 38
  • 39. Declaring And UsingDeclaring And Using VariablesVariables
  • 40. Declaring VariablesDeclaring Variables  When declaring a variable we:When declaring a variable we: Specify its typeSpecify its type Specify its name (called identifier)Specify its name (called identifier) May give it an initial valueMay give it an initial value  The syntax is the following:The syntax is the following:  Example:Example: <data_type> <identifier> [= <initialization>];<data_type> <identifier> [= <initialization>]; int height = 200;int height = 200; 40
  • 41. IdentifiersIdentifiers  Identifiers may consist of:Identifiers may consist of: Letters (Unicode)Letters (Unicode) Digits [0-9]Digits [0-9] Underscore "_"Underscore "_"  IdentifiersIdentifiers Can begin only with a letter or an underscoreCan begin only with a letter or an underscore Cannot be a C# keywordCannot be a C# keyword 41
  • 42. Identifiers (2)Identifiers (2)  IdentifiersIdentifiers Should have a descriptive nameShould have a descriptive name It is recommended to use only Latin lettersIt is recommended to use only Latin letters Should be neither too long nor too shortShould be neither too long nor too short  Note:Note: In C# small letters are considered different thanIn C# small letters are considered different than the capital letters (case sensitivity)the capital letters (case sensitivity) 42
  • 43. Identifiers – ExamplesIdentifiers – Examples  Examples of correct identifiers:Examples of correct identifiers:  Examples of incorrect identifiers:Examples of incorrect identifiers: int new;int new; // new is a keyword// new is a keyword int 2Pac;int 2Pac; // Cannot begin with a digit// Cannot begin with a digit int New = 2; // Here N is capitalint New = 2; // Here N is capital int _2Pac; // This identifiers begins with _int _2Pac; // This identifiers begins with _ string поздрав = "Hello"; // Unicode symbols usedstring поздрав = "Hello"; // Unicode symbols used // The following is more appropriate:// The following is more appropriate: string greeting = "Hello";string greeting = "Hello"; int n = 100; // Undescriptiveint n = 100; // Undescriptive int numberOfClients = 100; // Descriptiveint numberOfClients = 100; // Descriptive // Overdescriptive identifier:// Overdescriptive identifier: int numberOfPrivateClientOfTheFirm = 100;int numberOfPrivateClientOfTheFirm = 100; 43
  • 45. Assigning ValuesAssigning Values  Assigning of values to variablesAssigning of values to variables Is achieved by theIs achieved by the == operatoroperator  TheThe == operator hasoperator has Variable identifier on the leftVariable identifier on the left Value of the corresponding data type on theValue of the corresponding data type on the rightright Could be used in a cascade calling, whereCould be used in a cascade calling, where assigning is done from right to leftassigning is done from right to left 45
  • 46. Assigning Values – ExamplesAssigning Values – Examples  Assigning values example:Assigning values example: int firstValue = 5;int firstValue = 5; int secondValue;int secondValue; int thirdValue;int thirdValue; // Using an already declared variable:// Using an already declared variable: secondValue = firstValue;secondValue = firstValue; // The following cascade calling assigns// The following cascade calling assigns // 3 to firstValue and then firstValue// 3 to firstValue and then firstValue // to thirdValue, so both variables have// to thirdValue, so both variables have // the value 3 as a result:// the value 3 as a result: thirdValue = firstValue = 3; // Avoid this!thirdValue = firstValue = 3; // Avoid this! 46
  • 47. Initializing VariablesInitializing Variables  InitializingInitializing Is assigning of initial valueIs assigning of initial value Must be done before the variable is used!Must be done before the variable is used!  Several ways of initializing:Several ways of initializing: By using theBy using the newnew keywordkeyword By using a literal expressionBy using a literal expression By referring to an already initialized variableBy referring to an already initialized variable 47
  • 48. Initialization – ExamplesInitialization – Examples  Example of some initializations:Example of some initializations: // The following would assign the default// The following would assign the default // value of the int type to num:// value of the int type to num: int num = new int(); // num = 0int num = new int(); // num = 0 // This is how we use a literal expression:// This is how we use a literal expression: float heightInMeters = 1.74f;float heightInMeters = 1.74f; // Here we use an already initialized variable:// Here we use an already initialized variable: string greeting = "Hello World!";string greeting = "Hello World!"; string message = greeting;string message = greeting; 48
  • 51. What are Literals?What are Literals?  Literals are:Literals are: Representations of values in the source codeRepresentations of values in the source code  There are six types of literalsThere are six types of literals BooleanBoolean IntegerInteger RealReal CharacterCharacter StringString TheThe nullnull literalliteral 51
  • 52. Boolean and Integer LiteralsBoolean and Integer Literals  The boolean literals are:The boolean literals are: truetrue falsefalse  The integer literals:The integer literals: Are used for variables of typeAre used for variables of type intint,, uintuint,, longlong,, andand ulongulong Consist of digitsConsist of digits May have a sign (May have a sign (++,,--)) May be in a hexadecimal formatMay be in a hexadecimal format 52
  • 53. Integer LiteralsInteger Literals  Examples of integer literalsExamples of integer literals TheThe ''0x0x'' andand ''0X0X'' prefixes mean aprefixes mean a hexadecimal value, e.g.hexadecimal value, e.g. 0xA8F10xA8F1 TheThe ''uu'' andand ''UU'' suffixes mean asuffixes mean a ulongulong oror uintuint type, e.g.type, e.g. 12345678U12345678U TheThe ''ll'' andand ''LL'' suffixes mean asuffixes mean a longlong oror ulongulong type, e.g.type, e.g. 9876543L9876543L 53
  • 54. Integer Literals – ExampleInteger Literals – Example  Note: the letter ‘Note: the letter ‘ll’ is easily confused with the’ is easily confused with the digit ‘digit ‘11’ so it’s better to use ‘’ so it’s better to use ‘LL’!!!’!!! // The following variables are// The following variables are // initialized with the same value:// initialized with the same value: int numberInHex = -0x10;int numberInHex = -0x10; int numberInDec = -16;int numberInDec = -16; // The following causes an error,// The following causes an error, because 234u is of type uintbecause 234u is of type uint int unsignedInt = 234u;int unsignedInt = 234u; // The following causes an error,// The following causes an error, because 234L is of type longbecause 234L is of type long int longInt = 234L;int longInt = 234L; 54
  • 55. Real LiteralsReal Literals  The real literals:The real literals: Are used for values of typeAre used for values of type floatfloat,, doubledouble andand decimaldecimal May consist of digits, a sign and “May consist of digits, a sign and “..”” May be in exponential notation:May be in exponential notation: 6.02e+236.02e+23  The “The “ff” and “” and “FF” suffixes mean” suffixes mean floatfloat  The “The “dd” and “” and “DD” suffixes mean” suffixes mean doubledouble  The “The “mm” and “” and “MM” suffixes mean” suffixes mean decimaldecimal  The default interpretation isThe default interpretation is doubledouble 55
  • 56. Real Literals – ExampleReal Literals – Example  Example of incorrectExample of incorrect floatfloat literal:literal:  A correct way to assign floating-point valueA correct way to assign floating-point value (using also the exponential format):(using also the exponential format): 56 // The following causes an error// The following causes an error // because 12.5 is double by default// because 12.5 is double by default float realNumber = 12.5;float realNumber = 12.5; // The following is the correct// The following is the correct // way of assigning the value:// way of assigning the value: float realNumber = 12.5f;float realNumber = 12.5f; // This is the same value in exponential format:// This is the same value in exponential format: realNumber = 1.25e+7f;realNumber = 1.25e+7f;
  • 57. Character LiteralsCharacter Literals  The character literals:The character literals: Are used for values of theAre used for values of the charchar typetype Consist of two single quotes surrounding theConsist of two single quotes surrounding the character value:character value: ''<value><value>''  The value may be:The value may be: SymbolSymbol The code of the symbolThe code of the symbol Escaping sequenceEscaping sequence 57
  • 58. Escaping SequencesEscaping Sequences  Escaping sequences are:Escaping sequences are: Means of presenting a symbol that is usuallyMeans of presenting a symbol that is usually interpreted otherwise (likeinterpreted otherwise (like '')) Means of presenting system symbols (like theMeans of presenting system symbols (like the new line symbol)new line symbol)  Common escaping sequences are:Common escaping sequences are:  '' for single quotefor single quote "" for double quotefor double quote  for backslashfor backslash nn for new linefor new line  uXXXXuXXXX for denoting any other Unicode symbolfor denoting any other Unicode symbol 58
  • 59. Character Literals – ExampleCharacter Literals – Example  Examples of different character literals:Examples of different character literals: char symbol = 'a'; // An ordinary symbolchar symbol = 'a'; // An ordinary symbol symbol = 'u006F'; // Unicode symbol code insymbol = 'u006F'; // Unicode symbol code in // a hexadecimal format// a hexadecimal format symbol = 'u8449'; //symbol = 'u8449'; // 葉葉 ((Leaf in Traditional Chinese)Leaf in Traditional Chinese) symbol = '''; // Assigning the single quote symbolsymbol = '''; // Assigning the single quote symbol symbol = ''; // Assigning the backslash symbolsymbol = ''; // Assigning the backslash symbol symbol = 'n'; // Assigning new line symbolsymbol = 'n'; // Assigning new line symbol symbol = 't'; // Assigning TAB symbolsymbol = 't'; // Assigning TAB symbol symbol = "a"; // Incorrect: use single quotessymbol = "a"; // Incorrect: use single quotes 59
  • 60. String LiteralsString Literals  String literals:String literals: Are used for values of the string typeAre used for values of the string type Consist of two double quotes surrounding theConsist of two double quotes surrounding the value:value: ""<value><value>"" May have aMay have a @@ prefix which ignores the usedprefix which ignores the used escaping sequences:escaping sequences: @@"<value>""<value>"  The value is a sequence of character literalsThe value is a sequence of character literals string s = "I am a sting literal";string s = "I am a sting literal"; 60
  • 61. String Literals – ExampleString Literals – Example  Benefits of quoted strings (theBenefits of quoted strings (the @@ prefix):prefix):  In quoted stringsIn quoted strings "" is used instead ofis used instead of """"!! // Here is a string literal using escape sequences// Here is a string literal using escape sequences string quotation = ""Hello, Jude", he said.";string quotation = ""Hello, Jude", he said."; string path = "C:WINNTDartsDarts.exe";string path = "C:WINNTDartsDarts.exe"; // Here is an example of the usage of @// Here is an example of the usage of @ quotation = @"""Hello, Jimmy!"", she answered.";quotation = @"""Hello, Jimmy!"", she answered."; path = @"C:WINNTDartsDarts.exe";path = @"C:WINNTDartsDarts.exe"; string str = @"somestring str = @"some text";text"; 61
  • 64. Nullable TypesNullable Types  NullableNullable types are instances of thetypes are instances of the System.NullableSystem.Nullable structstruct Wrapper over theWrapper over the primitiveprimitive typestypes E.g.E.g. int?int?,, double?double?, etc., etc.  NullabeNullabe type can represent the normal rangetype can represent the normal range of values for its underlying value type, plus anof values for its underlying value type, plus an additionaladditional nullnull valuevalue  Useful when dealing withUseful when dealing with DatabasesDatabases or otheror other structures that have default valuestructures that have default value nullnull
  • 65. Nullable Types – ExampleNullable Types – Example int? someInteger = null;int? someInteger = null; Console.WriteLine(Console.WriteLine( "This is the integer with Null value -> " + someInteger);"This is the integer with Null value -> " + someInteger); someInteger = 5;someInteger = 5; Console.WriteLine(Console.WriteLine( "This is the integer with value 5 -> " + someInteger);"This is the integer with value 5 -> " + someInteger); double? someDouble = null;double? someDouble = null; Console.WriteLine(Console.WriteLine( "This is the real number with Null value -> ""This is the real number with Null value -> " + someDouble);+ someDouble); someDouble = 2.5;someDouble = 2.5; Console.WriteLine(Console.WriteLine( "This is the real number with value 5 -> " +"This is the real number with value 5 -> " + someDouble);someDouble); Example withExample with IntegerInteger:: Example withExample with DoubleDouble::
  • 67. Questions?Questions? Primitive DataPrimitive Data Types andVariablesTypes andVariables http://academy.telerik.com
  • 68. ExercisesExercises 1.1. Declare five variables choosing for each of them theDeclare five variables choosing for each of them the most appropriate of the typesmost appropriate of the types bytebyte,, sbytesbyte,, shortshort,, ushortushort,, intint,, uintuint,, longlong,, ulongulong to represent theto represent the following values: 52130, -115, 4825932, 97, -10000.following values: 52130, -115, 4825932, 97, -10000. 2.2. Which of the following values can be assigned to aWhich of the following values can be assigned to a variable of typevariable of type floatfloat and which to a variable ofand which to a variable of typetype doubledouble: 34.567839023, 12.345, 8923.1234857,: 34.567839023, 12.345, 8923.1234857, 3456.091?3456.091? 3.3. Write a program that safely compares floating-pointWrite a program that safely compares floating-point numbers with precision ofnumbers with precision of 0.0000010.000001.. 68
  • 69. Exercises (2)Exercises (2) 4.4. Declare an integer variable and assign it with theDeclare an integer variable and assign it with the value 254 in hexadecimal format. Use Windowsvalue 254 in hexadecimal format. Use Windows Calculator to find its hexadecimal representation.Calculator to find its hexadecimal representation. 5.5. Declare a character variable and assign it with theDeclare a character variable and assign it with the symbol that has Unicode code 72. Hint: first use thesymbol that has Unicode code 72. Hint: first use the Windows Calculator to find the hexadecimalWindows Calculator to find the hexadecimal representation of 72.representation of 72. 6.6. Declare a boolean variable calledDeclare a boolean variable called isFemaleisFemale andand assign an appropriate value corresponding to yourassign an appropriate value corresponding to your gender.gender. 69
  • 70. Exercises (3)Exercises (3) 7.7. Declare twoDeclare two stringstring variables and assign them withvariables and assign them with “Hello” and “World”. Declare an“Hello” and “World”. Declare an objectobject variable andvariable and assign it with the concatenation of the first twoassign it with the concatenation of the first two variables (mind adding an interval). Declare a thirdvariables (mind adding an interval). Declare a third stringstring variable and initialize it with the value of thevariable and initialize it with the value of the object variable (you should perform type casting).object variable (you should perform type casting). 8.8. Declare twoDeclare two stringstring variables and assign them withvariables and assign them with following value:following value: Do the above in two different ways: with and withoutDo the above in two different ways: with and without using quoted strings.using quoted strings. The "use" of quotations causes difficulties.The "use" of quotations causes difficulties. 70
  • 71. Exercises (4)Exercises (4) 9.9. Write a program thatWrite a program that prints an isosceles triangle ofprints an isosceles triangle of 9 copyright symbols9 copyright symbols ©©. Use Windows Character. Use Windows Character Map to find the Unicode code of theMap to find the Unicode code of the ©© symbol.symbol. 10.10. A marketing firm wants to keep record of itsA marketing firm wants to keep record of its employees. Each record would have the followingemployees. Each record would have the following characteristics – first name, family name,characteristics – first name, family name, age,age, gender (m or f), ID number,gender (m or f), ID number, unique employeeunique employee number (27560000 to 27569999). Declare thenumber (27560000 to 27569999). Declare the variables needed to keep the information for avariables needed to keep the information for a single employee using appropriate data typessingle employee using appropriate data types andand descriptive names.descriptive names. 11.11. Declare two integer variables and assign them withDeclare two integer variables and assign them with 5 and 10 and after that exchange their values.5 and 10 and after that exchange their values. 71