Primitive Data Types and Variables - WordPress.com...Jan 02, 2019  · Table of Contents 1....

Preview:

Citation preview

Primitive Data Primitive Data Types and VariablesTypes and Variables

Creating and Running Your First C# ProgramCreating and Running Your First C# Program

Svetlin NakovSvetlin NakovTelerik CorporationTelerik Corporationwww.telerik.comwww.telerik.com

Table of ContentsTable of Contents1.1. Primitive Data TypesPrimitive Data Types

Integer Integer Floating-Point / Decimal Floating-PointFloating-Point / Decimal Floating-Point BooleanBoolean CharacterCharacter StringString ObjectObject

2.2. Declaring and Using VariablesDeclaring and Using Variables IdentifiersIdentifiers Declaring Variables and Assigning ValuesDeclaring Variables and Assigning Values LiteralsLiterals

P NullableNullable types types2

Primitive Data TypesPrimitive Data Types

How Computing Works?How Computing Works?

Computers are machines that process dataComputers are machines that process data

Data is stored in the computer memory in Data is stored in the computer memory in variablesvariables

Variables have Variables have namename, , data type data type and and valuevalue

Example of variable definition and assignment Example of variable definition and assignment in C#in C#

int count = 5;int count = 5;Data typeData type

Variable nameVariable name

Variable valueVariable value4

What Is a Data Type?What Is a Data Type? A A 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 the Defines 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: 06

Integer TypesInteger Types

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 of Have 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 type type

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 use Depending 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, or Console.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

Integer TypesInteger TypesLive DemoLive Demo

Floating-Point and Decimal Floating-Point and Decimal Floating-Point TypesFloating-Point Types

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 precision Have 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:

float float (±1.5 × 10(±1.5 × 10−45−45 to ±3.4 × 10 to ±3.4 × 103838): 32-bits, ): 32-bits, precision of 7 digitsprecision of 7 digits

double double (±5.0 × 10(±5.0 × 10−324−324 to ±1.7 × 10 to ±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:

Is Is 0.0F0.0F for the for the floatfloat typetype

Is Is 0.0D0.0D for the for the doubledouble typetype

15

PI Precision – ExamplePI Precision – Example See below the difference in precision when using See below the difference in precision when using floatfloat and and doubledouble::

NOTE: The “NOTE: The “ff” suffix in the first statement!” suffix in the first statement!

Real numbers are by default interpreted as Real numbers are by default interpreted as doubledouble!!

One should One should explicitlyexplicitly convert them to convert 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 the Abnormalities in the Floating-Point CalculationsFloating-Point Calculations

Sometimes abnormalities can be observed Sometimes abnormalities can be observed when using floating-point numberswhen using floating-point numbers

Comparing floating-point numbers can not be Comparing floating-point numbers can not be performed directly with the performed directly with the ==== operator operator

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 × 10 to ±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 of The 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 Decimal Floating-Point and Decimal Floating-Point TypesFloating-Point Types

Live DemoLive Demo

Boolean TypeBoolean Type

The Boolean Data TypeThe Boolean Data Type The The Boolean data typeBoolean data type::

Is declared by the Is declared by the boolbool keyword keyword

Has two possible values: Has two possible values: truetrue and and falsefalse

Is useful in logical expressionsIs useful in logical expressions

The default value is The default value is falsefalse

21

Boolean Values – ExampleBoolean Values – Example Example of boolean variables taking values of Example of boolean variables taking values of truetrue or or 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

Boolean TypeBoolean TypeLive DemoLive Demo

Character TypeCharacter Type

The Character Data TypeThe Character Data Type The The character data typecharacter data type::

Represents symbolic informationRepresents symbolic information

Is declared by the Is declared by the charchar keyword keyword

Gives each symbol a corresponding integer codeGives each symbol a corresponding integer code

Has a Has a '\0''\0' default value default value

Takes 16 bits of memory (from Takes 16 bits of memory (from U+0000U+0000 to to U+FFFFU+FFFF))

25

Characters and CodesCharacters and Codes The example below shows that every symbol The 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

Character TypeCharacter TypeLive DemoLive Demo

String TypeString Type

The String Data TypeThe String Data Type The The string data typestring data type::

Represents a sequence of charactersRepresents a sequence of characters

Is declared by the Is declared by the stringstring keyword keyword

Has a default value Has 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 the Using the ++ operator operator

string s = "Microsoft .NET Framework";string s = "Microsoft .NET Framework";

29

Saying Hello – ExampleSaying Hello – Example Concatenating the two names of a person to Concatenating the two names of a person to

obtain his full name:obtain his full name:

NOTE: a space is missing between the two NOTE: 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

String TypeString TypeLive DemoLive Demo

Object TypeObject Type

The Object TypeThe Object Type The object type:The object type:

Is declared by the Is declared by the objectobject keyword keyword

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 different Example 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

ObjectsObjectsLive DemoLive Demo

What Is a Variable?What Is a Variable? A variable is a:A variable is a:

Placeholder of information that can usually be Placeholder 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 Using Declaring 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 than In 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 keywordint 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 capitalint _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; // Undescriptiveint numberOfClients = 100; // Descriptiveint numberOfClients = 100; // Descriptive

// Overdescriptive identifier:// Overdescriptive identifier:int numberOfPrivateClientOfTheFirm = 100;int numberOfPrivateClientOfTheFirm = 100;

43

Assigning ValuesAssigning Values Assigning of values to variablesAssigning of values to variables

Is achieved by the Is achieved by the == operator operator

The The == operator has operator has

Variable identifier on the leftVariable identifier on the left

Value of the corresponding data type on the Value of the corresponding data type on the rightright

Could be used in a cascade calling, where Could 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 the By using the newnew keyword keyword

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 and Assigning and Initializing VariablesInitializing Variables

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

The The nullnull literal literal51

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 type Are used for variables of type intint, , uintuint, , longlong, , and and ulongulong

Consist of digitsConsist of digits

May have a sign (May have a sign (++,,--))

May be in a hexadecimal formatMay be in a hexadecimal format52

Integer LiteralsInteger Literals Examples of integer literalsExamples of integer literals

The The ''0x0x'' and and ''0X0X'' prefixes mean a prefixes mean a hexadecimal value, e.g. hexadecimal value, e.g. 0xA8F10xA8F1

The The ''uu'' and and ''UU'' suffixes mean a suffixes mean a ulongulong or or uintuint type, e.g. type, e.g. 12345678U12345678U

The The ''ll'' and and ''LL'' suffixes mean a suffixes mean a longlong or or 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 uintint 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 longint longInt = 234L;int longInt = 234L;

54

Real LiteralsReal Literals The real literals:The real literals:

Are used for values of type Are used for values of type floatfloat, , doubledouble and and 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 is The default interpretation is doubledouble55

Real Literals – ExampleReal Literals – Example Example of incorrect Example of incorrect floatfloat literal: literal:

A correct way to assign floating-point value A 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 defaultfloat 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 the Are used for values of the charchar typetype

Consist of two single quotes surrounding the Consist 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 usually Means of presenting a symbol that is usually interpreted otherwise (like interpreted otherwise (like ''))

Means of presenting system symbols (like the Means of presenting system symbols (like the new line symbol)new line symbol)

Common escaping sequences are:Common escaping sequences are:

\'\' for single quote for single quote \"\" for double quote for double quote

\\\\ for backslash for backslash \n\n for new linefor new line

\uXXXX\uXXXX for denoting any other Unicode symbolfor denoting any other Unicode symbol58

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 in symbol = '\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 the Consist of two double quotes surrounding the value: value: ""<value><value>""

May have a May have a @@ prefix which ignores the used prefix 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 (the Benefits of quoted strings (the @@ prefix): prefix):

In quoted strings In quoted strings \"\" is used instead of is used instead of """"!!

// Here is a string literal using escape sequences// Here is a string literal using escape sequencesstring quotation = "\"Hello, Jude\", he said.";string quotation = "\"Hello, Jude\", he said.";string path = "C:\\WINNT\\Darts\\Darts.exe";string path = "C:\\WINNT\\Darts\\Darts.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:\WINNT\Darts\Darts.exe";path = @"C:\WINNT\Darts\Darts.exe";

string str = @"somestring str = @"sometext";text";

61

String LiteralsString LiteralsLive DemoLive Demo

Nullable TypesNullable Types

63

Nullable TypesNullable Types NullableNullable types are instances of the types are instances of the System.NullableSystem.Nullable structstruct

Wrapper over the Wrapper over the primitiveprimitive typestypes

E.g. E.g. int?int?, , double?double?, etc., etc. NullabeNullabe type can represent the normal range type can represent the normal range

of values for its underlying value type, plus an of values for its underlying value type, plus an additional additional nullnull value value

Useful when dealing with Useful when dealing with DatabasesDatabases or other or other structures that have default value structures 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 with Example with IntegerInteger::

Example with Example with DoubleDouble::

Nullable TypesNullable TypesLive DemoLive Demo

66

Questions?Questions?

Primitive Data Primitive Data Types and VariablesTypes and Variables

http://academy.telerik.com

ExercisesExercises

1.1. Declare five variables choosing for each of them the Declare five variables choosing for each of them the most appropriate of the types most appropriate of the types bytebyte, , sbytesbyte, , shortshort, , ushortushort, , intint, , uintuint, , longlong, , ulongulong to represent the to 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 a Which of the following values can be assigned to a variable of type variable of type floatfloat and which to a variable of and which to a variable of type type 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-point Write a program that safely compares floating-point numbers with precision of numbers with precision of 0.0000010.000001..

68

Exercises (2)Exercises (2)

1.1. Declare an integer variable and assign it with the Declare an integer variable and assign it with the value 254 in hexadecimal format. Use Windows value 254 in hexadecimal format. Use Windows Calculator to find its hexadecimal representation.Calculator to find its hexadecimal representation.

2.2. Declare a character variable and assign it with the Declare a character variable and assign it with the symbol that has Unicode code 72. Hint: first use the symbol that has Unicode code 72. Hint: first use the Windows Calculator to find the hexadecimal Windows Calculator to find the hexadecimal representation of 72.representation of 72.

3.3. Declare a boolean variable called Declare a boolean variable called isFemaleisFemale and and assign an appropriate value corresponding to your assign an appropriate value corresponding to your gender.gender.

69

Exercises (3)Exercises (3)1.1. Declare two Declare two stringstring variables and assign them with variables and assign them with

“Hello” and “World”. Declare an “Hello” and “World”. Declare an objectobject variable and variable and assign it with the concatenation of the first two assign it with the concatenation of the first two variables (mind adding an interval). Declare a third variables (mind adding an interval). Declare a third stringstring variable and initialize it with the value of the variable and initialize it with the value of the object variable (you should perform type casting).object variable (you should perform type casting).

2.2. Declare two Declare two stringstring variables and assign them with variables and assign them with following value:following value:

Do the above in two different ways: with and without Do 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)1.1. Write a program thatWrite a program that prints an isosceles triangle of prints an isosceles triangle of

9 copyright symbols 9 copyright symbols ©©. Use Windows Character . Use Windows Character Map to find the Unicode code of the Map to find the Unicode code of the ©© symbol. symbol.

2.2. A marketing firm wants to keep record of its A marketing firm wants to keep record of its employees. Each record would have the following employees. 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 employee unique employee number (27560000 to 27569999). Declare the number (27560000 to 27569999). Declare the variables needed to keep the information for a variables needed to keep the information for a single employee using appropriate data typessingle employee using appropriate data types andand descriptive names.descriptive names.

3.3. Declare two integer variables and assign them with Declare 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

Recommended