Presentation is loading. Please wait.

Presentation is loading. Please wait.

BIM313 – Advanced Programming Techniques Strings and Functions 1.

Similar presentations


Presentation on theme: "BIM313 – Advanced Programming Techniques Strings and Functions 1."— Presentation transcript:

1 BIM313 – Advanced Programming Techniques Strings and Functions 1

2 Contents More on Variables – Type Conversions – Enumerations – Structs – Arrays – String Operations Functions and Delegates 2

3 Type Conversion Examples – string to int or int to string – double to int (rounding operations) Implicit Conversions – No data loss – Trust in the compiler Explicit Conversions – Data may be lost – Approve the compiler 3

4 Implicit Conversions Implicit conversion requires no work on your part and no additional code. ushort and char types are effectively interchangeable, because both store a number between 0 and 65535. 4

5 Implicit Conversion Example char ch = ‘a’; ushort num; num = ch; Console.WriteLine(“ch = {0}, num = {1}”, ch, num); 5 ch = a, num = 97

6 Implicit Type Conversions TypeCan Safely Be Converted To charushort, int, uint, long, ulong, float, double, decimal byteshort, ushort, int, uint, long, ulong, float, double, decimal sbyteshort, int, long, float, double, decimal shortint, long, float, double, decimal ushortint, uint, long, ulong, float, double, decimal intlong, float, double, decimal uintlong, ulong, float, double, decimal longfloat, double, decimal ulongfloat, double, decimal floatdouble - decimal- 6

7 Explicit Conversions Wide types can’t be converted to narrow types (e.g. conversion from short to byte) In such cases, compiler gives error: – Cannot implicitly convert type ‘short’ to ‘byte’. An explicit conversion exists (are you missing a cast?) If you are sure that you really want to make the conversion, use the explicit conversion: – OK, I know you’ve warned me about doing this, but I’ll take responsibility for what happens. 7

8 Example byte b; short s = 7; b = s; Console.WriteLine(“b = {0}, s = {1}”, b, s); 8 Cannot implicitly convert type ‘short’ to ‘byte’. An explicit conversion exists (are you missing a cast?)

9 Solution byte b; short s = 7; b = (byte) s; Console.WriteLine(“b = {0}, s = {1}”, b, s); 9 b = 7, s = 7

10 Range Problem byte b; short s = 281; b = (byte) s; Console.WriteLine(“b = {0}, s = {1}”, b, s); 10 b = 25, s = 281 281 doesn’t fit into the byte range! Amount of overflow from 256!

11 Explicit Conversions by “Convert” Another method to make explicit conversion is using the “Convert” methods: – int i = Convert.ToInt32(val) – float f = Convert.ToSingle(val) – double d = Convert.ToDouble(val) – string s = Convert.ToString(val) Here, val can be most types of variable. 11

12 A Note on Explicit Conversions If the explicit conversion is impossible, then your program is not compiled. – string s = “12.34”; – double d = (double)s; If the explicit conversion is possible but an error occurs in runtime, then an Exception occurs (i.e. your program crashes ) – string s = “abcd”; – double d = Convert.ToDouble(s); 12

13 Complex Variable Types Enumerations (enum) Structures (struct) Arrays 13

14 Enumerations (enum) The type double is used to store fractional numbers bool type is used to store true or false In real life, there are other existences: – Orientation: North, South, East, West – Week Days: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday – Months: January, February, …, December These types can be implemented by enumerations in C#. 14

15 enum Syntax Definition: enum {, … } 15

16 enum Syntax Declaring variables: ; Assigning values: =. ; 16

17 enum Example namespace Ch05Ex02 { enum Orientation { North, South, East, West } class Program { static void Main(string[] args) { Orientation myDirection = Orientation.North; Console.WriteLine("myDirection = {0}", myDirection); } 17

18 Advanced Topics on enum (1) Each values in an enumeration are stored as integers, starting from 0 and incremented by 1 – Console.WriteLine("{0} = {1}, {2} = {3}", Orientation.North, (int)Orientation.North, Orientation.South, (int)Orientation.South); 18 North = 0, South = 1

19 Advanced Topics on enum (2) You can change underlying integer values of some enumerations Unspecified values are automatically generated by incrementing last value enum Orientation {North=1, South, East=4, West=8} 19 North = 1, South = 2, East = 4, West = 8

20 Advanced Topics on enum (3) You can change the underlying type from the default type (int) to byte, short, and long (and their signed and unsigned versions) enum Orientation : byte {North, South, East, West} Console.WriteLine((byte)Orientation.North) 20

21 Structs Structs are data structures that are composed of several pieces of data, possibly of different types. – Student records (name, age, birth year, etc.) – Route (orientation, distance, etc.) 21

22 Defining Structs struct { ; … } 22

23 Example struct Route { public Orientation Direction; public double Distance; } 23

24 Declaring a struct variable Syntax: ; Example: Route myRoute; myRoute.Orientation = Orientation.North; myRoute.Distance = 2.5; 24

25 Example route myRoute; int myDirection = -1; double myDistance; Console.WriteLine("1) North\n2) South\n3) East\n4) West"); do { Console.WriteLine("Select a direction:"); myDirection = Convert.ToInt32(Console.ReadLine()); } while (myDirection 4); Console.WriteLine("Input a distance:"); myDistance = Convert.ToDouble(Console.ReadLine()); myRoute.direction = (orientation)myDirection; myRoute.distance = myDistance; Console.WriteLine("myRoute specifies a direction of {0} and a " + "distance of {1}", myRoute.direction, myRoute.distance); 25

26 Arrays Use arrays to store large number of data of same type – int grade1, grade2, grade3, …; – int[] grades; Arrays make some operations simple – Think of the case where you want to initialize all values to zero. 26

27 Declaring Arrays Syntax: [] ; Example: – int[] myIntArray; – string[] myStringArray; In this declaration, only a reference without any elements is created 27

28 Initialization int[] arr = new int[5]; – an array of 5 elements with default values (0 for numbers) int[] arr = {5, 9, 10, 2, 99}; – an array of 5 elements with initial values int[] arr = new int[5] {5, 9, 10, 2, 99}; – an array of 5 elements with initial values int[] arr = new int[10] {5, 9, 10, 2, 99}; – an array of 10 elements but only first five of them are initialized (the rest are initialized to the default value) 28

29 Accessing Array Elements arr[5] = 10; – 10 is assigned to the 6 th element of the array – Indexing starts from 0 (not 1) int num = arr[5]; – 6 th element of the array is assigned to a variable for (int i = 0; i < arr.Length; i++) { Console.WriteLine(arr[i]); } – All array elements are displayed on the screen. 29

30 Example string[] friendNames = { "Robert Barwell", "Mike Parry", "Jeremy Beacock" }; Console.WriteLine("Here are {0} of my friends:", friendNames.Length); for (int i = 0; i < friendNames.Length; i++) { Console.WriteLine(friendNames[i]); } 30

31 Same example with foreach string[] friendNames = { "Robert Barwell", "Mike Parry", "Jeremy Beacock" }; Console.WriteLine("Here are {0} of my friends:", friendNames.Length); foreach (string friendName in friendNames) { Console.WriteLine(friendName); } 31

32 Multidimensional Arrays int[,] mat = new int[5, 8]; – Access as mat[i, j] int[,,] cube = new int[3, 5, 8]; int[,] mat = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}; – Two-dimensional array of size 3x4 (3 rows, 4 columns) 32

33 String Operations (1) Concatenation – str = str1 + str2; Accessing a char at specified location – char ch = str[3]; // 4 th element is assigned to ch Getting the length – int size = str.Length; Getting all chars into a char array – char[] chars = str.ToCharArray(); 33

34 String Operations (2) Changing to upper or lower cases – str2 = str1.ToUpper(); – str2 = str1.ToLower(); These methods doesn’t change str1! If you want to change str1 itself, use this: – str1 = str1.ToLower(); Remove white spaces (space, tab, new line) at the beginning and at the end: – str2 = str1.Trim(); 34

35 String Operations (3) Remove white spaces only at the beginning: – str2 = str1.TrimStart(); Remove white spaces only at the end: – str2 = str1.TrimEnd(); Substrings: – string str1 = “advanced”; – string str2 = str1.SubString(2, 3); // “van” – str2 = str1.SubString(2); // “vanced” 35

36 Split() You can split a string using the Split() method The Split() method returns a string array It takes separator chars as a char array If no parameters are supplied, it splits the string according to the white spaces string str = “This is a pencil”; string[] arr = str.Split(); foreach (string s in arr) { Console.WriteLine(s); } 36 This is a pencil

37 Using separators in Split() string str = “1,2,3,4,5”; char[] separator = {‘,’}; string[] arr = str.Split(separator); foreach (string s in arr) { Console.WriteLine(s); } 37 1234512345

38 Other String Operations Examine the following string methods by yourself: – CompareTo, Equals – Contains – StartsWith, EndsWith – IndexOf, IndexOfAny, LastIndexOf, LastIndexOfAny – PadLeft, PadRight – Remove – Replace 38

39 Functions Some tasks may need to be performed at several points in a program – e.g. finding the highest number in an array Solution: Write the code in a function and call it several times In object-oriented programming languages, functions of objects are named as methods 39

40 Function Example class Program { static void DrawBorder() { Console.WriteLine(“+--------+”); } static void Main(string[] args) { DrawBorder(); Console.WriteLine(“| Hello! |”); DrawBorder(); } 40 +--------+ | Hello! | +--------+ Don’t forget to use the word ‘static’!

41 Functions that return a value static int ReadAge() { Console.Write(“Enter your age: ”); int age = int.Parse(Console.ReadLine()); if (age < 1) return 1; else if (age > 120) return 120; else return age; } 41

42 Functions that take parameters static double Product(double a, double b) { return a * b; } 42

43 Functions that take array as parameter class Program { static int MaxValue(int[] intArray) { int maxVal = intArray[0]; for (int i = 1; i < intArray.Length; i++) { if (intArray[i] > maxVal) maxVal = intArray[i]; } return maxVal; } static void Main(string[] args) { int[] myArray = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 }; int maxVal = MaxValue(myArray); Console.WriteLine("The maximum value in myArray is {0}", maxVal); } 43

44 Parameter Arrays If your function may take variable amount of parameters, then you can use the parameter arrays – Think of Console.WriteLine(format, params) – You can use any amount of parameters after the format string Parameter arrays can be declared with the keyword params Parameter array should be the last parameter in the parameter list of the function 44

45 params Example class Program { static int SumVals(params int[] vals) { int sum = 0; foreach (int val in vals) { sum += val; } return sum; } static void Main(string[] args) { int sum = SumVals(1, 5, 2, 9, 8); Console.WriteLine("Summed Values = {0}", sum); } 45

46 Call By Value and Call By Reference If you change a value-type parameter in the function, it doesn’t affect the value in the main function – because, only the value is transferred However, if you change a reference-type parameter’s elements, then the argument in the main function is also changed – because the object itself is transferred You can think arrays as reference-types 46

47 Call By Value static void ShowDouble(int val) { val *= 2; Console.WriteLine(“val doubled = {0}”, val); } static void Main(string[] args) { int myNumber = 5; ShowDouble(myNumber); Console.WriteLine(“myNumber in main: ” + myNumber); } 47 val doubled = 10 myNumber in main: 5

48 Call By Reference static void ChangeFirst(int[] arr) { arr[0] = 99; } static void Main(string[] args) { int[] myArr = {1, 2, 3, 4, 5}; DisplayArray(myArr); ChangeFirst(myArr); DisplayArray(myArr); } 48 1 2 3 4 5 99 2 3 4 5

49 ref and out You can change the value of argument in the Main function via a function using the ref keyword You can declare a parameter as the output of a function with the out keyword – out parameters does not have to be initialized before the function call (their values are set by the function) 49

50 ref Example static void ShowDouble(ref int val) { val *= 2; Console.WriteLine(“val doubled = {0}”, val); } static void Main(string[] args) { int myNumber = 5; ShowDouble(ref myNumber); Console.WriteLine(“myNumber in main: ” + myNumber); } 50 val doubled = 10 myNumber in main: 10

51 out Example static void FindAvgAndSum(int[] arr, out double avg, out int sum) { sum = 0; foreach (int num in arr) { sum += num; } avg = (double) sum / arr.Lenght; } static void Main(string[] args) { int sum; double avg; int[] myArray = {3, 4, 8, 2, 7}; FindAvgAndSum(myArray, out avg, out sum); } 51

52 Another Example for out static int MaxValue(int[] intArray, out int maxIndex) { int maxVal = intArray[0]; maxIndex = 0; for (int i = 1; i < intArray.Length; i++) { if (intArray[i] > maxVal) { maxVal = intArray[i]; maxIndex = i; } return maxVal; } 52

53 Variable Scope Variables in a functions are not accessible by other functions – they are called local variables The variables declared in the class definition are accessible by all functions in the class – they are called global variables – they should be static so that static functions can access them Variables declared in a block (for, while, {}, etc.) are only accessible in that block 53

54 The Main Function The Main function is the entry point in a C# program It takes a string array parameter, whose elements are called command-line parameters The following declarations of Main are all valid: – static void Main() – static void Main(string[] args) – static int Main() – static int Main(string[] args) 54

55 Command-Line Parameters class Program { static void Main(string[] args) { Console.WriteLine("{0} command line arguments were specified:", args.Length); foreach (string arg in args) { Console.WriteLine(arg); } 55

56 Specifying Command-Line Arguments in Visual Studio Right-click on the project name in the Solution Explorer window and select Properties Select the Debug pane Write command-line arguments into the box Run the application 56

57 Specifying Command-Line Arguments in Command Prompt Open a command prompt Go to the folder of the executable output of the program Write the name of the executable followed by the command-line arguments – prog.exe 256 myfile.txt “a longer argument” 57

58 struct Functions struct CustomerName { public string firstName, lastName; public string Name() { return firstName + " " + lastName; } 58

59 Calling struct Function CustomerName myCustomer; myCustomer.firstName = "John"; myCustomer.lastName = "Franklin"; Console.WriteLine(myCustomer.Name()); 59

60 Overloading Functions A function may have several signatures – i.e. same function name but different parameters – e.g. Console.WriteLine() Intellisense feature of the Visual Studio helps us to select the correct function 60

61 Example 1 static int MaxValue(int[] intArray) { … } static double MaxValue(double[] doubleArray) { … } static void Main(string[] args) { int[] arr1 = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 }; double[] arr2 = { 0.1, 0.8, 0.3, 1.6, 0.2}; int maxVal1 = MaxValue(arr1); double maxVal2 = MaxValue(arr2); } 61

62 Example 2 static void func(ref int val) { … } static void func(int val) { … } func(ref val); func(val); 62 Signatures are different, so usage is valid! The ref keyword differentiates the functions!

63 Delegates References to functions – “Function Pointers” in C and C++ Declaration: Specify a return type and parameter list Assignment: Convert function reference to a delegate Calling: Just use the delegate’s name 63

64 Delegate Example delegate double MyDelegate(double num1, double num2); static double Multiply(double param1, double param2) { return param1 * param2; } static double Divide(double param1, double param2) { return param1 / param2; } 64 Declaration

65 Delegate Example (continued) static void Main(string[] args) { MyDelegate process; double param1 = 5; double param2 = 3, process = new MyDelegate(Multiply); Console.WriteLine("Result: {0}", process(param1, param2)); process = new MyDelegate(Divide); Console.WriteLine("Result: {0}", process(param1, param2)); } 65

66 Easier Way static void Main(string[] args) { MyDelegate process; double param1 = 5; double param2 = 3, process = Multiply; Console.WriteLine("Result: {0}", process(param1, param2)); process = Divide; Console.WriteLine("Result: {0}", process(param1, param2)); } 66


Download ppt "BIM313 – Advanced Programming Techniques Strings and Functions 1."

Similar presentations


Ads by Google