4. 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
5. 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
6. Integer Types – ExampleInteger Types – Example
Measuring timeMeasuring time
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, or {2}Console.WriteLine("{0} centuries is {1} years, or {2}
days, or {3} hours.", centuries, years, days, hours);days, or {3} hours.", centuries, years, days, hours);
7. 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
8. Fixed-Point TypesFixed-Point Types
There is a special fixed-point real numberThere is a special fixed-point real number
type:type:
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 calculations with low loss ofUsed for financial calculations with low loss of
precisionprecision
No round-off errorsNo round-off errors
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)
9. PI Precision – ExamplePI Precision – Example
See below the difference in precision whenSee below the difference in precision when
usingusing 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);
10. 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
done directly with thedone directly with the ==== operatoroperator
Example:Example:
float a = 1.0f;float a = 1.0f;
float b = 0.33f;float b = 0.33f;
float sum = 1.33f;float 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);
11. The Boolean Data TypeThe Boolean Data Type
The Boolean Data Type:The Boolean 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
12. Boolean Values – ExampleBoolean Values – Example
Here we can see how boolean variables takeHere we can see how boolean variables take
values ofvalues 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
13. The Character Data TypeThe Character Data Type
The Character Data Type:The Character Data Type:
Represents symbolic informationRepresents symbolic information
Is declared by theIs declared by the charchar keywordkeyword
Gives each symbol a corresponding integerGives each symbol a corresponding integer
codecode
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))
14. Characters and CodesCharacters and Codes
The example below shows that every symbolThe example below shows that every symbol
has an its unique code:has an its unique 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);
15. The String Data TypeThe String Data Type
The String Data Type:The String 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
string s = "Microsoft .NET Framework";string s = "Microsoft .NET Framework";
16. 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}!", firstName);Console.WriteLine("Hello, {0}!", 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);
17. The Object TypeThe Object Type
The object type:The object type:
Is declared by theIs declared by the objectobject keywordkeyword
Is the “parent” of all other typesIs the “parent” of all other types
Can take any types of values according to theCan take any types of values according to the
needsneeds
18. 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);
20. 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;
21. 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
22. 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)
23. 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;
25. 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
26. 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;
27. Real LiteralsReal Literals
The real literals:The real literals:
Are used for values of typeAre used for values of type floatfloat andand doubledouble
May consist of digits, a sign and “May consist of digits, a sign and “..””
May be in exponential formattingMay be in exponential formatting
The “The “ff” and “” and “FF” suffixes mean” suffixes mean floatfloat
The “The “dd” and “” and “DD” suffixes mean” suffixes mean doubledouble
The default interpretation isThe default interpretation is doubledouble
28. 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):
28
// 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+1f;realNumber = 1.25e+1f;
29. 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
value:value: ''<value><value>''
The value may be:The value may be:
SymbolSymbol
The code of the symbolThe code of the symbol
Escaping sequenceEscaping sequence
30. 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
31. 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 = 'u0061'; // Unicode symbol code insymbol = 'u0061'; // Unicode symbol code in
// a hexadecimal format// a hexadecimal format
symbol = '''; // Assigning the single quote symbolsymbol = '''; // Assigning the single quote symbol
symbol = ''; // Assigning the backslash symbolsymbol = ''; // Assigning the backslash symbol
symbol = "a"; // Incorrect: use single quotessymbol = "a"; // Incorrect: use single quotes
32. String LiteralsString Literals
String literals:String literals:
Are used for values of the stringAre used for values of the string
typetype
Consist of two double quotesConsist of two double quotes
surrounding the value:surrounding the value: ""<value><value>""
May have aMay have a @@ prefix which ignoresprefix which ignores
the used escaping sequencesthe used escaping sequences
The value is a sequence ofThe value is a sequence of
character literalscharacter literals
33. 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";
37. Operators Precedence (2)Operators Precedence (2)
PrecedencePrecedence OperatorsOperators
HigherHigher ||
&&&&
||||
?:?:
LowestLowest
= *= /= %= += -= <<= >>= &== *= /= %= += -= <<= >>= &=
^= |=^= |=
37
Parenthesis operator always has highestParenthesis operator always has highest
precedenceprecedence
Note: prefer usingNote: prefer using parenthesesparentheses, even when it, even when it
seems stupid to do soseems stupid to do so
38. Arithmetic OperatorsArithmetic Operators
Arithmetic operatorsArithmetic operators ++,, --,, ** are the same as inare the same as in
mathmath
Division operatorDivision operator // if used on integers returnsif used on integers returns
integer (without rounding)integer (without rounding)
Remainder operatorRemainder operator %% returns the remainderreturns the remainder
from division of integersfrom division of integers
The special addition operatorThe special addition operator ++++ increments aincrements a
variablevariable
39. Arithmetic Operators – ExampleArithmetic Operators – Example
int squarePerimeter = 17;int squarePerimeter = 17;
double squareSide = squarePerimeter/4.0;double squareSide = squarePerimeter/4.0;
double squareArea = squareSide*squareSide;double squareArea = squareSide*squareSide;
Console.WriteLine(squareSide); // 4.25Console.WriteLine(squareSide); // 4.25
Console.WriteLine(squareArea); // 18.0625Console.WriteLine(squareArea); // 18.0625
int a = 5;int a = 5;
int b = 4;int b = 4;
Console.WriteLine( a + b ); // 9Console.WriteLine( a + b ); // 9
Console.WriteLine( a + b++ ); // 9Console.WriteLine( a + b++ ); // 9
Console.WriteLine( a + b ); // 10Console.WriteLine( a + b ); // 10
Console.WriteLine( a + (++b) ); // 11Console.WriteLine( a + (++b) ); // 11
Console.WriteLine( a + b ); // 11Console.WriteLine( a + b ); // 11
Console.WriteLine(11 / 3); // 3Console.WriteLine(11 / 3); // 3
Console.WriteLine(11 % 3); // 2Console.WriteLine(11 % 3); // 2
Console.WriteLine(12 / 3); // 4Console.WriteLine(12 / 3); // 4
42. Bitwise OperatorsBitwise Operators
Bitwise operatorBitwise operator ~~ turns allturns all 00 toto 11 and alland all 11 toto 00
LikeLike !! for boolean expressions but bit by bitfor boolean expressions but bit by bit
The operatorsThe operators ||,, && andand ^^ behave likebehave like ||||,, &&&&
andand ^^ for boolean expressions but bit by bitfor boolean expressions but bit by bit
TheThe <<<< andand >>>> move the bits (left or right)move the bits (left or right)
Behavior of the operatorsBehavior of the operators||,, && andand ^^::
OperationOperation || || || || && && && && ^^ ^^ ^^ ^^
Operand1Operand1 00 00 11 11 00 00 11 11 00 00 11 11
Operand2Operand2 00 11 00 11 00 11 00 11 00 11 00 11
ResultResult 00 11 11 11 00 00 00 11 00 11 11 00
43. Bitwise Operators (2)Bitwise Operators (2)
Bitwise operators are used on integer numbersBitwise operators are used on integer numbers
((bytebyte,, sbytesbyte,, intint,, uintuint,, longlong,, ulongulong))
Bitwise operators are applied bit by bitBitwise operators are applied bit by bit
Examples:Examples:
ushort a = 3; // 00000011ushort a = 3; // 00000011
ushort b = 5; // 00000101ushort b = 5; // 00000101
Console.WriteLine( a | b); // 00000111Console.WriteLine( a | b); // 00000111
Console.WriteLine( a & b); // 00000001Console.WriteLine( a & b); // 00000001
Console.WriteLine( a ^ b); // 00000110Console.WriteLine( a ^ b); // 00000110
Console.WriteLine(~a & b); // 00000100Console.WriteLine(~a & b); // 00000100
Console.WriteLine( a<<1 ); // 00000110Console.WriteLine( a<<1 ); // 00000110
Console.WriteLine( a>>1 ); // 00000001Console.WriteLine( a>>1 ); // 00000001
44. Comparison OperatorsComparison Operators
Comparison operators are used to compareComparison operators are used to compare
variablesvariables
====,, <<,, >>,, >=>=,, <=<=,, !=!=
Comparison operators example:Comparison operators example:
int a = 5;int a = 5;
int b = 4;int b = 4;
Console.WriteLine(a >= b); // TrueConsole.WriteLine(a >= b); // True
Console.WriteLine(a != b); // TrueConsole.WriteLine(a != b); // True
Console.WriteLine(a > b); // FalseConsole.WriteLine(a > b); // False
Console.WriteLine(a == b); // FalseConsole.WriteLine(a == b); // False
Console.WriteLine(a == a); // TrueConsole.WriteLine(a == a); // True
Console.WriteLine(a != ++b); // FalseConsole.WriteLine(a != ++b); // False
45. Assignment OperatorsAssignment Operators
Assignment operators are used to assign aAssignment operators are used to assign a
value to a variable ,value to a variable ,
==,, +=+=,, -=-=,, |=|=,, ......
Assignment operators example:Assignment operators example:
int x = 6;int x = 6;
int y = 4;int y = 4;
Console.WriteLine(y *= 2); // 8Console.WriteLine(y *= 2); // 8
int z = y = 3; // y=3 and z=3int z = y = 3; // y=3 and z=3
Console.WriteLine(z); // 3Console.WriteLine(z); // 3
Console.WriteLine(x |= 1); // 7Console.WriteLine(x |= 1); // 7
Console.WriteLine(x += 3); // 10Console.WriteLine(x += 3); // 10
Console.WriteLine(x /= 2); // 5Console.WriteLine(x /= 2); // 5
46. Other OperatorsOther Operators
String concatenation operatorString concatenation operator ++ is used tois used to
concatenate stringsconcatenate strings
If the second operand is not a string, it isIf the second operand is not a string, it is
converted to string automaticallyconverted to string automatically
string first = "First";string first = "First";
string second = "Second";string second = "Second";
Console.WriteLine(first + second);Console.WriteLine(first + second);
// FirstSecond// FirstSecond
string output = "The number is : ";string output = "The number is : ";
int number = 5;int number = 5;
Console.WriteLine(output + number);Console.WriteLine(output + number);
// The number is : 5// The number is : 5
47. Other Operators (2)Other Operators (2)
Member access operatorMember access operator .. is used to accessis used to access
object membersobject members
Square bracketsSquare brackets [][] are used with arraysare used with arrays
indexers and attributesindexers and attributes
ParenthesesParentheses (( )) are used to override theare used to override the
default operator precedencedefault operator precedence
Class cast operatorClass cast operator (type)(type) is used to cast oneis used to cast one
compatible type to anothercompatible type to another
48. Other Operators (3)Other Operators (3)
Conditional operatorConditional operator ?:?: has the formhas the form
(if(if bb is true then the result isis true then the result is xx else the result iselse the result is yy))
TheThe newnew operator is used to create new objectsoperator is used to create new objects
TheThe typeoftypeof operator returnsoperator returns System.TypeSystem.Type
object (the reflection of a type)object (the reflection of a type)
TheThe isis operator checks if an object isoperator checks if an object is
compatible with given typecompatible with given type
b ? x : yb ? x : y
49. Other Operators – ExampleOther Operators – Example
Using some other operators:Using some other operators:
int a = 6;int a = 6;
int b = 4;int b = 4;
Console.WriteLine(a > b ? "a>b" : "b>=a"); // a>bConsole.WriteLine(a > b ? "a>b" : "b>=a"); // a>b
Console.WriteLine((long) a); // 6Console.WriteLine((long) a); // 6
int c = b = 3; // b=3; followed by c=3;int c = b = 3; // b=3; followed by c=3;
Console.WriteLine(c); // 3Console.WriteLine(c); // 3
Console.WriteLine(a is int); // TrueConsole.WriteLine(a is int); // True
Console.WriteLine((a+b)/2); // 4Console.WriteLine((a+b)/2); // 4
Console.WriteLine(typeof(int)); // System.Int32Console.WriteLine(typeof(int)); // System.Int32
int d = new int();int d = new int();
Console.WriteLine(d); // 0Console.WriteLine(d); // 0
50. Type ConversionsType Conversions
Example ofExample of implicitimplicit andand explicitexplicit conversions:conversions:
Note: explicit conversion may be used even ifNote: explicit conversion may be used even if
not required by the compilernot required by the compiler
float heightInMeters = 1.74f; // Explicit conversionfloat heightInMeters = 1.74f; // Explicit conversion
double maxHeight = heightInMeters; // Implicitdouble maxHeight = heightInMeters; // Implicit
double minHeight = (double) heightInMeters; //double minHeight = (double) heightInMeters; //
ExplicitExplicit
float actualHeight = (float) maxHeight; // Explicitfloat actualHeight = (float) maxHeight; // Explicit
float maxHeightFloat = maxHeight; // Compilationfloat maxHeightFloat = maxHeight; // Compilation
error!error!
52. ExpressionsExpressions
Expressions are sequences of operators,Expressions are sequences of operators,
literals and variables that are evaluated toliterals and variables that are evaluated to
some valuesome value
Examples:Examples:
int r = (150-20) / 2 + 5;int r = (150-20) / 2 + 5;
// Expression for calculation of circle area// Expression for calculation of circle area
double surface = Math.PI * r * r;double surface = Math.PI * r * r;
// Expression for calculation of circle perimeter// Expression for calculation of circle perimeter
double perimeter = 2 * Math.PI * r;double perimeter = 2 * Math.PI * r;
53. Using to the ConsoleUsing to the Console
Printing / Reading Strings and NumbersPrinting / Reading Strings and Numbers
53
54. The Console ClassThe Console Class
Provides methods for input and outputProvides methods for input and output
InputInput
Read(…)Read(…) – reads a single character– reads a single character
ReadLine(…)ReadLine(…) – reads a single line of– reads a single line of
characterscharacters
OutputOutput
Write(…)Write(…) – prints the specified– prints the specified
argument on the consoleargument on the console
WriteLine(…WriteLine(…)) – prints specified data to the– prints specified data to the
console and moves to the next lineconsole and moves to the next line
54
55. Console.Write(…)Console.Write(…)
Printing more than one variable using aPrinting more than one variable using a
formatting stringformatting string
55
int a = 15;int a = 15;
......
Console.Write(a); // 15Console.Write(a); // 15
Printing an integer variablePrinting an integer variable
double a = 15.5;double a = 15.5;
int b = 14;int b = 14;
......
Console.Write("{0} + {1} = {2}", a, b, a + b);Console.Write("{0} + {1} = {2}", a, b, a + b);
// 15.5 + 14 = 29.5// 15.5 + 14 = 29.5
Next print operation will start from the same lineNext print operation will start from the same line
56. Console.WriteLine(…)Console.WriteLine(…)
56
Printing more than one variable using aPrinting more than one variable using a
formatting stringformatting string
string str = "Hello C#!";string str = "Hello C#!";
......
Console.WriteLine(str);Console.WriteLine(str);
Printing a string variablePrinting a string variable
string name = "Marry";string name = "Marry";
int year = 1987;int year = 1987;
......
Console.Write("{0} was born in {1}.", name, year);Console.Write("{0} was born in {1}.", name, year);
// Marry was born in 1987.// Marry was born in 1987.
Next printing will start from the next lineNext printing will start from the next line
57. Printing to the Console – ExamplePrinting to the Console – Example
57
static void Main()static void Main()
{{
string name = "Peter";string name = "Peter";
int age = 18;int age = 18;
string town = "Sofia";string town = "Sofia";
Console.Write("{0} is {1} years old from {2}.",Console.Write("{0} is {1} years old from {2}.",
name, age, town);name, age, town);
// Result: Peter is 18 years old from Sofia.// Result: Peter is 18 years old from Sofia.
Console.Write("This is on the same line!");Console.Write("This is on the same line!");
Console.WriteLine("Next sentence will be" +Console.WriteLine("Next sentence will be" +
" on a new line.");" on a new line.");
Console.WriteLine("Bye, bye, {0} from {1}.",Console.WriteLine("Bye, bye, {0} from {1}.",
name, town);name, town);
}}
58. Reading from the ConsoleReading from the Console
We use the console to read information fromWe use the console to read information from
the command linethe command line
We can read:We can read:
CharactersCharacters
StringsStrings
Numeral types (after conversion)Numeral types (after conversion)
To read from the console we use the methodsTo read from the console we use the methods
Console.Read()Console.Read() andand Console.ReadLine()Console.ReadLine()
58
59. Console.ReadLine()Console.ReadLine()
Gets a line of charactersGets a line of characters
Returns aReturns a stringstring valuevalue
ReturnsReturns nullnull if the end of the input is reachedif the end of the input is reached
59
Console.Write("Please enter your first name: ");Console.Write("Please enter your first name: ");
string firstName = Console.ReadLine();string firstName = Console.ReadLine();
Console.Write("Please enter your last name: ");Console.Write("Please enter your last name: ");
string lastName = Console.ReadLine();string lastName = Console.ReadLine();
Console.WriteLine("Hello, {0} {1}!",Console.WriteLine("Hello, {0} {1}!",
firstName, lastName);firstName, lastName);
60. Reading Numeral TypesReading Numeral Types
Numeral types can not be read directly from theNumeral types can not be read directly from the
consoleconsole
To read a numeral type do following:To read a numeral type do following:
1.1. RRead a string valueead a string value
2.2. Convert (parse) it to the required numeral typeConvert (parse) it to the required numeral type
int.Parse(string)int.Parse(string) – parses a– parses a stringstring toto intint
60
string str = Console.ReadLine()string str = Console.ReadLine()
int number = int.Parse(str);int number = int.Parse(str);
Console.WriteLine("You entered: {0}", number);Console.WriteLine("You entered: {0}", number);
61. Reading Numeral Types (2)Reading Numeral Types (2)
Another way to parseAnother way to parse stringstring to numeralto numeral
type is to usetype is to use int.TryParse(…)int.TryParse(…) methodmethod
Sets default value for the type if the parse failsSets default value for the type if the parse fails
ReturnsReturns boolbool
TrueTrue if the parse is successfullif the parse is successfull
FalseFalse if it failsif it fails
61
int a;int a;
string line = Console.ReadLine();string line = Console.ReadLine();
int.TryParse(line, out a);int.TryParse(line, out a);
The result from the parse will be assigned toThe result from the parse will be assigned to
the variablethe variable parseResultparseResult
62. Converting Strings to NumbersConverting Strings to Numbers
Numeral types have a methodNumeral types have a method Parse(…)Parse(…) forfor
extracting the numeral value from a stringextracting the numeral value from a string
int.Parse(string)int.Parse(string) –– stringstring intint
longlong.Parse(string).Parse(string) –– stringstring longlong
floatfloat.Parse(string).Parse(string) –– stringstring floatfloat
CausesCauses FormatExceptionFormatException in case ofin case of errorerror
62
string s = "123";string s = "123";
int i = int.Parse(s); // i = 123int i = int.Parse(s); // i = 123
long l = long.Parse(s); // l = 123Llong l = long.Parse(s); // l = 123L
string invalid = "xxx1845";string invalid = "xxx1845";
int value = int.Parse(invalid); // FormatExceptionint value = int.Parse(invalid); // FormatException
64. TheThe ifif StatementStatement
The most simple conditional statementThe most simple conditional statement
Enables you to test for a conditionEnables you to test for a condition
Branch to different parts of the codeBranch to different parts of the code
depending on the resultdepending on the result
The simplest form of anThe simplest form of an ifif statement:statement:
64
if (condition)if (condition)
{{
statements;statements;
}}
65. TheThe ifif Statement – ExampleStatement – Example
65
static void Main()static void Main()
{{
Console.WriteLine("Enter two numbers.");Console.WriteLine("Enter two numbers.");
int biggerNumber = int.Parse(Console.ReadLine());int biggerNumber = int.Parse(Console.ReadLine());
int smallerNumber = int.Parse(Console.ReadLine());int smallerNumber = int.Parse(Console.ReadLine());
if (smallerNumber > biggerNumber)if (smallerNumber > biggerNumber)
{{
biggerNumber = smallerNumber;biggerNumber = smallerNumber;
}}
Console.WriteLine("The greater number is: {0}",Console.WriteLine("The greater number is: {0}",
biggerNumber);biggerNumber);
}}
66. TheThe if-elseif-else StatementStatement
More complex and useful conditional statementMore complex and useful conditional statement
Executes one branch if the condition is true, andExecutes one branch if the condition is true, and
another if it is falseanother if it is false
The simplest form of anThe simplest form of an if-elseif-else statement:statement:
66
if (expression)if (expression)
{{
statement1;statement1;
}}
elseelse
{{
statement2;statement2;
}}
67. if-elseif-else Statement – ExampleStatement – Example
Checking a number if it is odd or evenChecking a number if it is odd or even
67
string s = Console.ReadLine();string s = Console.ReadLine();
int number = int.Parse(s);int number = int.Parse(s);
if (number % 2 == 0)if (number % 2 == 0)
{{
Console.WriteLine("This number is even.");Console.WriteLine("This number is even.");
}}
elseelse
{{
Console.WriteLine("This number is odd.");Console.WriteLine("This number is odd.");
}}
68. NestedNested ifif StatementsStatements
ifif andand if-elseif-else statements can bestatements can be nestednested,,
i.e. used inside anotheri.e. used inside another ifif oror elseelse statementstatement
EveryEvery elseelse corresponds to its closestcorresponds to its closest
precedingpreceding ifif
68
if (expression)if (expression)
{{
if (expression)if (expression)
{{
statement;statement;
}}
elseelse
{{
statement;statement;
}}
}}
elseelse
statement;statement;
69. NestedNested ifif Statements – ExampleStatements – Example
69
if (first == second)if (first == second)
{{
Console.WriteLine(Console.WriteLine(
"These two numbers are equal.");"These two numbers are equal.");
}}
elseelse
{{
if (first > second)if (first > second)
{{
Console.WriteLine(Console.WriteLine(
"The first number is bigger.");"The first number is bigger.");
}}
elseelse
{{
Console.WriteLine("The second is bigger.");Console.WriteLine("The second is bigger.");
}}
}}
70. TheThe switch-caseswitch-case StatementStatement
Selects for execution a statement from a listSelects for execution a statement from a list
depending on the value of thedepending on the value of the switchswitch
expressionexpression
70
switch (day)switch (day)
{{
case 1: Console.WriteLine("Monday"); break;case 1: Console.WriteLine("Monday"); break;
case 2: Console.WriteLine("Tuesday"); break;case 2: Console.WriteLine("Tuesday"); break;
case 3: Console.WriteLine("Wednesday"); break;case 3: Console.WriteLine("Wednesday"); break;
case 4: Console.WriteLine("Thursday"); break;case 4: Console.WriteLine("Thursday"); break;
case 5: Console.WriteLine("Friday"); break;case 5: Console.WriteLine("Friday"); break;
case 6: Console.WriteLine("Saturday"); break;case 6: Console.WriteLine("Saturday"); break;
case 7: Console.WriteLine("Sunday"); break;case 7: Console.WriteLine("Sunday"); break;
default: Console.WriteLine("Error!"); break;default: Console.WriteLine("Error!"); break;
}}
72. How To Use While Loop?How To Use While Loop?
The simplest and most frequently used loopThe simplest and most frequently used loop
The repeat conditionThe repeat condition
Returns a boolean result ofReturns a boolean result of truetrue oror falsefalse
Also calledAlso called loop conditionloop condition
while (condition)while (condition)
{{
statements;statements;
}}
73. While Loop – ExampleWhile Loop – Example
int counter = 0;int counter = 0;
while (counter < 10)while (counter < 10)
{{
Console.WriteLine("Number : {0}", counter);Console.WriteLine("Number : {0}", counter);
counter++;counter++;
}}
74. Using Do-While LoopUsing Do-While Loop
Another loop structure is:Another loop structure is:
The block of statements is repeatedThe block of statements is repeated
While the boolean loop condition holdsWhile the boolean loop condition holds
The loop is executed at least onceThe loop is executed at least once
dodo
{{
statements;statements;
}}
while (condition);while (condition);
75. Factorial – ExampleFactorial – Example
Calculating N factorialCalculating N factorial
static void Main()static void Main()
{{
int n = Convert.ToInt32(Console.ReadLine());int n = Convert.ToInt32(Console.ReadLine());
int factorial = 1;int factorial = 1;
dodo
{{
factorial *= n;factorial *= n;
n--;n--;
}}
while (n > 0);while (n > 0);
Console.WriteLine("n! = " + factorial);Console.WriteLine("n! = " + factorial);
}}
76. For LoopsFor Loops
The typicalThe typical forfor loop syntax is:loop syntax is:
Consists ofConsists of
Initialization statementInitialization statement
Boolean test expressionBoolean test expression
Update statementUpdate statement
Loop body blockLoop body block
for (initialization; test; update)for (initialization; test; update)
{{
statements;statements;
}}
77. N^M – ExampleN^M – Example
CalculatingCalculating nn to powerto power mm (denoted as(denoted as n^mn^m):):
static void Main()static void Main()
{{
int n = int.Parse(Console.ReadLine());int n = int.Parse(Console.ReadLine());
int m = int.Parse(Console.ReadLine());int m = int.Parse(Console.ReadLine());
decimal result = 1;decimal result = 1;
for (int i=0; i<m; i++)for (int i=0; i<m; i++)
{{
result *= n;result *= n;
}}
Console.WriteLine("n^m = " + result);Console.WriteLine("n^m = " + result);
}}
78. For-Each LoopsFor-Each Loops
The typicalThe typical foreachforeach loop syntax is:loop syntax is:
Iterates over all elements of a collectionIterates over all elements of a collection
TheThe elementelement is the loop variable that takesis the loop variable that takes
sequentially all collection valuessequentially all collection values
TheThe collectioncollection can be list, array or othercan be list, array or other
group of elements of the same typegroup of elements of the same type
foreach (Type element in collection)foreach (Type element in collection)
{{
statements;statements;
}}
79. foreachforeach Loop – ExampleLoop – Example
Example ofExample of foreachforeach loop:loop:
string[] days = new string[] {string[] days = new string[] {
"Monday", "Tuesday", "Wednesday", "Thursday","Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday" };"Friday", "Saturday", "Sunday" };
foreach (String day in days)foreach (String day in days)
{{
Console.WriteLine(day);Console.WriteLine(day);
}}
The above loop iterates of the array of daysThe above loop iterates of the array of days
The variableThe variable dayday takes all its valuestakes all its values
80. Nested LoopsNested Loops
A composition of loops is called aA composition of loops is called a nested loopnested loop
A loop inside another loopA loop inside another loop
Example:Example:
for (initialization; test; update)for (initialization; test; update)
{{
for (initialization; test; update)for (initialization; test; update)
{{
statements;statements;
}}
……
}}
81. Nested Loops – ExamplesNested Loops – Examples
Print all combinations from TOTO 6/49Print all combinations from TOTO 6/49
static void Main()static void Main()
{{
int i1, i2, i3, i4, i5, i6;int i1, i2, i3, i4, i5, i6;
for (i1 = 1; i1 <= 44; i1++)for (i1 = 1; i1 <= 44; i1++)
for (i2 = i1 + 1; i2 <= 45; i2++)for (i2 = i1 + 1; i2 <= 45; i2++)
for (i3 = i2 + 1; i3 <= 46; i3++)for (i3 = i2 + 1; i3 <= 46; i3++)
for (i4 = i3 + 1; i4 <= 47; i4++)for (i4 = i3 + 1; i4 <= 47; i4++)
for (i5 = i4 + 1; i5 <= 48; i5++)for (i5 = i4 + 1; i5 <= 48; i5++)
for (i6 = i5 + 1; i6 <= 49; i6++)for (i6 = i5 + 1; i6 <= 49; i6++)
Console.WriteLine("{0} {1} {2} {3} {4}Console.WriteLine("{0} {1} {2} {3} {4}
{5}",{5}",
i1, i2, i3, i4, i5, i6);i1, i2, i3, i4, i5, i6);
}}
Warning:Warning:
execution of thisexecution of this
code could takecode could take
too long time.too long time.
83. What are Arrays?What are Arrays?
An array is a sequence of elementsAn array is a sequence of elements
All elements are of the same typeAll elements are of the same type
The order of the elements is fixedThe order of the elements is fixed
Has fixed size (Has fixed size (Array.LengthArray.Length))
0 1 2 3 40 1 2 3 4Array of 5Array of 5
elementselements
ElementElement
indexindex
ElementElement
of anof an
arrayarray
…… …… …… …… ……
84. Declaring ArraysDeclaring Arrays
Declaration defines the type of the elementsDeclaration defines the type of the elements
Square bracketsSquare brackets [][] mean "array"mean "array"
Examples:Examples:
Declaring array of integers:Declaring array of integers:
Declaring array of strings:Declaring array of strings:
int[] myIntArray;int[] myIntArray;
string[] myStringArray;string[] myStringArray;
85. Creating ArraysCreating Arrays
Use the operatorUse the operator newnew
Specify array lengthSpecify array length
Example creating (allocating) array of 5Example creating (allocating) array of 5
integers:integers:
myIntArray = new int[5];myIntArray = new int[5];
myIntArraymyIntArray
managed heapmanaged heap
(dynamic memory)(dynamic memory)
0 1 2 3 40 1 2 3 4
…… …… …… …… ……
86. Creating and Initializing ArraysCreating and Initializing Arrays
Creating and initializing can be done together:Creating and initializing can be done together:
TheThe newnew operator is not required when usingoperator is not required when using
curly brackets initializationcurly brackets initialization
myIntArray = {1, 2, 3, 4, 5};myIntArray = {1, 2, 3, 4, 5};
myIntArraymyIntArray
managed heapmanaged heap
(dynamic memory)(dynamic memory)
0 1 2 3 40 1 2 3 4
…… …… …… …… ……
87. Creating Array – ExampleCreating Array – Example
Creating an array that contains the names ofCreating an array that contains the names of
the days of the weekthe days of the week
string[] daysOfWeek =string[] daysOfWeek =
{{
"Monday","Monday",
"Tuesday","Tuesday",
"Wednesday","Wednesday",
"Thursday","Thursday",
"Friday","Friday",
"Saturday","Saturday",
"Sunday""Sunday"
};};
88. How to Access Array Element?How to Access Array Element?
Array elements are accessed using the squareArray elements are accessed using the square
brackets operatorbrackets operator [][] (indexer)(indexer)
Array indexer takes element’s index asArray indexer takes element’s index as
parameterparameter
The first element has indexThe first element has index 00
The last element has indexThe last element has index Length-1Length-1
Array elements can be retrieved and changedArray elements can be retrieved and changed
by theby the [][] operatoroperator
89. Reversing an Array – ExampleReversing an Array – Example
Reversing the contents of an arrayReversing the contents of an array
int[] array = new int[] {1, 2, 3, 4, 5};int[] array = new int[] {1, 2, 3, 4, 5};
// Get array size// Get array size
int length = array.Length;int length = array.Length;
// Declare and create the reversed array// Declare and create the reversed array
int[] reversed = new int[length];int[] reversed = new int[length];
// Initialize the reversed array// Initialize the reversed array
for (int index = 0; index < length; index++)for (int index = 0; index < length; index++)
{{
reversed[length-index-1] = array[index];reversed[length-index-1] = array[index];
}}
90. Processing Arrays:Processing Arrays: foreachforeach
HowHow foreachforeach loop works?loop works?
typetype – the type of the element– the type of the element
valuevalue – local name of variable– local name of variable
arrayarray – processing array– processing array
Used when no indexing is neededUsed when no indexing is needed
All elements are accessed one by oneAll elements are accessed one by one
Elements can not be modified (read only)Elements can not be modified (read only)
foreach (type value in array)foreach (type value in array)
91. Processing ArraysProcessing Arrays UsingUsing
foreachforeach – Example– Example
Print all elements of aPrint all elements of a string[]string[] array:array:
string[] capitals =string[] capitals =
{{
"Sofia","Sofia",
"Washington","Washington",
"London","London",
"Paris""Paris"
};};
foreach (string capital in capitals)foreach (string capital in capitals)
{{
Console.WriteLine(capital);Console.WriteLine(capital);
}}
92. Multidimensional ArraysMultidimensional Arrays
Multidimensional arraysMultidimensional arrays have more than onehave more than one
dimension (2, 3, …)dimension (2, 3, …)
The most important multidimensional arraysThe most important multidimensional arrays
are the 2-dimensionalare the 2-dimensional
Known asKnown as matricesmatrices oror tablestables
Example of matrix of integers with 2 rows andExample of matrix of integers with 2 rows and
4 columns:4 columns:
55 00 -2-2 44
55 66 77 88
0 1 2 3
0
1
93. Declaring and CreatingDeclaring and Creating
Multidimensional ArraysMultidimensional Arrays
Declaring multidimensional arrays:Declaring multidimensional arrays:
Creating a multidimensional arrayCreating a multidimensional array
UseUse newnew keywordkeyword
Must specify the size of each dimensionMust specify the size of each dimension
int[,] intMatrix;int[,] intMatrix;
float[,] floatMatrix;float[,] floatMatrix;
string[,,] strCube;string[,,] strCube;
int[,] intMatrix = new int[3, 4];int[,] intMatrix = new int[3, 4];
float[,] floatMatrix = new float[8, 2];float[,] floatMatrix = new float[8, 2];
string[,,] stringCube = new string[5, 5, 5];string[,,] stringCube = new string[5, 5, 5];
94. Creating and InitializingCreating and Initializing
Multidimensional ArraysMultidimensional Arrays
Creating and initializing with valuesCreating and initializing with values
multidimensional array:multidimensional array:
Matrices are represented by a list of rowsMatrices are represented by a list of rows
Rows consist of list of valuesRows consist of list of values
The first dimension comes first, the secondThe first dimension comes first, the second
comes next (inside the first)comes next (inside the first)
int[,] matrix =int[,] matrix =
{{
{1, 2, 3, 4}, // row 0 values{1, 2, 3, 4}, // row 0 values
{5, 6, 7, 8}, // row 1 values{5, 6, 7, 8}, // row 1 values
}; // The matrix size is 2 x 4 (2 rows, 4 cols)}; // The matrix size is 2 x 4 (2 rows, 4 cols)
95. Reading Matrix – ExampleReading Matrix – Example
Reading a matrix from the consoleReading a matrix from the console
int rows = int.Parse(Console.ReadLine());int rows = int.Parse(Console.ReadLine());
int cols = int.Parse(Console.ReadLine());int cols = int.Parse(Console.ReadLine());
int[,] matrix = new int[rows, cols];int[,] matrix = new int[rows, cols];
for (int row=0; row<rows; row++)for (int row=0; row<rows; row++)
{{
for (int col=0; col<cols; col++)for (int col=0; col<cols; col++)
{{
Console.Write("matrix[{0},{1}] = ",Console.Write("matrix[{0},{1}] = ",
row, col);row, col);
matrix[row, col] =matrix[row, col] =
int.Parse(Console.ReadLine());int.Parse(Console.ReadLine());
}}
}}
96. Printing Matrix – ExamplePrinting Matrix – Example
Printing a matrix on the console:Printing a matrix on the console:
for (int row=0; row<matrix.GetLength(0); row++)for (int row=0; row<matrix.GetLength(0); row++)
{{
for (int col=0; col<matrix.GetLength(1); col++)for (int col=0; col<matrix.GetLength(1); col++)
{{
Console.Write("{0} ", matrix[row, col]);Console.Write("{0} ", matrix[row, col]);
}}
Console.WriteLine();Console.WriteLine();
}}
98. What is a Method?What is a Method?
AA methodmethod is a kind of building block thatis a kind of building block that
solves a small problemsolves a small problem
A piece of code that has a name and can beA piece of code that has a name and can be
called from the other codecalled from the other code
Can take parameters and return a valueCan take parameters and return a value
Methods allow programmers to constructMethods allow programmers to construct
large programs from simple pieceslarge programs from simple pieces
Methods are also known asMethods are also known as functionsfunctions,,
proceduresprocedures, and, and subroutinessubroutines
98
99. using System;using System;
class MethodExampleclass MethodExample
{{
static void PrintLogo()static void PrintLogo()
{{
Console.WriteLine("Telerik Corp.");Console.WriteLine("Telerik Corp.");
Console.WriteLine("www.telerik.com");Console.WriteLine("www.telerik.com");
}}
static void Main()static void Main()
{{
// ...// ...
}}
}}
Declaring and Creating MethodsDeclaring and Creating Methods
99
Methods are always declared inside aMethods are always declared inside a classclass
Main()Main() is also a method like all othersis also a method like all others
100. Calling MethodsCalling Methods
To call a method, simply use:To call a method, simply use:
The method’s nameThe method’s name
Parentheses (don’t forget them!)Parentheses (don’t forget them!)
A semicolon (A semicolon (;;))
This will execute the code in the method’sThis will execute the code in the method’s
body and will result in printing the following:body and will result in printing the following:
100
PrintLogo();PrintLogo();
Telerik Corp.Telerik Corp.
www.telerik.comwww.telerik.com
101. Defining and UsingDefining and Using
Method ParametersMethod Parameters
Method’s behavior depends on itsMethod’s behavior depends on its
parametersparameters
Parameters can be of any typeParameters can be of any type
intint,, doubledouble,, stringstring, etc., etc.
101
static void PrintSign(int number)static void PrintSign(int number)
{{
if (number > 0)if (number > 0)
Console.WriteLine("Positive");Console.WriteLine("Positive");
else if (number < 0)else if (number < 0)
Console.WriteLine("Negative");Console.WriteLine("Negative");
elseelse
Console.WriteLine("Zero");Console.WriteLine("Zero");
}}
102. Defining and UsingDefining and Using
Method Parameters (2)Method Parameters (2)
Methods can have as many parameters asMethods can have as many parameters as
needed:needed:
The following syntax is not valid:The following syntax is not valid:
102
static void PrintMax(float number1, float number2)static void PrintMax(float number1, float number2)
{{
float max = number1;float max = number1;
if (number2 > number1)if (number2 > number1)
max = number2;max = number2;
Console.WriteLine("Maximal number: {0}", max);Console.WriteLine("Maximal number: {0}", max);
}}
static void PrintMax(float number1, number2)static void PrintMax(float number1, number2)
103. Calling MethodsCalling Methods
with Parameterswith Parameters
To call a method and pass values to itsTo call a method and pass values to its
parameters:parameters:
Use the method’s name, followed by a list ofUse the method’s name, followed by a list of
expressions for each parameterexpressions for each parameter
Examples:Examples:
103
PrintSign(-5);PrintSign(-5);
PrintSign(balance);PrintSign(balance);
PrintSign(2+3);PrintSign(2+3);
PrintMax(100, 200);PrintMax(100, 200);
PrintMax(oldQuantity * 1.5, quantity * 2);PrintMax(oldQuantity * 1.5, quantity * 2);
104. Returning Values From MethodsReturning Values From Methods
A method canA method can returnreturn a value to its callera value to its caller
Returned value:Returned value:
Can be assigned to a variable:Can be assigned to a variable:
Can be used in expressions:Can be used in expressions:
Can be passed to another method:Can be passed to another method:
104
string message = Console.ReadLine();string message = Console.ReadLine();
// Console.ReadLine() returns a string// Console.ReadLine() returns a string
float price = GetPrice() * quantity * 1.20;float price = GetPrice() * quantity * 1.20;
int age = int.Parse(Console.ReadLine());int age = int.Parse(Console.ReadLine());
105. Defining MethodsDefining Methods
That Return a ValueThat Return a Value
Instead ofInstead of voidvoid, specify the type of data to return, specify the type of data to return
Methods can return any type of data (Methods can return any type of data (intint,,
stringstring, array, etc.), array, etc.)
voidvoid methods do not return anythingmethods do not return anything
The combination of method's name andThe combination of method's name and
parameters is calledparameters is called method signaturemethod signature
UseUse returnreturn keyword to return a resultkeyword to return a result
105
static int Multiply(int firstNum, int secondNum)static int Multiply(int firstNum, int secondNum)
{{
return firstNum * secondNum;return firstNum * secondNum;
}}
106. TheThe returnreturn StatementStatement
TheThe returnreturn statement:statement:
Immediately terminates method’s executionImmediately terminates method’s execution
Returns specified expression to the callerReturns specified expression to the caller
Example:Example:
To terminateTo terminate voidvoid method, use just:method, use just:
Return can be used several times in a methodReturn can be used several times in a method
bodybody
106
return -1;
return;
107. TemperatureTemperature
Conversion – ExampleConversion – Example
Convert temperature from Fahrenheit toConvert temperature from Fahrenheit to
Celsius:Celsius:
107
static double FahrenheitToCelsius(double degrees)static double FahrenheitToCelsius(double degrees)
{{
double celsius = (degrees - 32) * 5 / 9;double celsius = (degrees - 32) * 5 / 9;
return celsius;return celsius;
}}
static void Main()static void Main()
{{
Console.Write("Temperature in Fahrenheit: ");Console.Write("Temperature in Fahrenheit: ");
double t = Double.Parse(Console.ReadLine());double t = Double.Parse(Console.ReadLine());
t = FahrenheitToCelsius(t);t = FahrenheitToCelsius(t);
Console.Write("Temperature in Celsius: {0}", t);Console.Write("Temperature in Celsius: {0}", t);
}}