bim313 – advanced programming techniques strings and functions 1

Click here to load reader

Post on 02-Jan-2016




1 download

Embed Size (px)


EEM336 Microprocessors I

BIM313 Advanced Programming TechniquesStrings and Functions1ContentsMore on VariablesType ConversionsEnumerationsStructsArraysString OperationsFunctions and Delegates2Type ConversionExamplesstring to int or int to stringdouble to int (rounding operations)Implicit ConversionsNo data lossTrust in the compilerExplicit ConversionsData may be lostApprove the compiler3Implicit ConversionsImplicit 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.4Implicit Conversion Examplechar ch = a;ushort num;num = ch;Console.WriteLine(ch = {0}, num = {1}, ch, num);

5ch = a, num = 97Implicit Type ConversionsTypeCan Safely Be Converted Tocharushort, int, uint, long, ulong, float, double, decimalbyteshort, ushort, int, uint, long, ulong, float, double, decimalsbyteshort, int, long, float, double, decimalshortint, long, float, double, decimalushortint, uint, long, ulong, float, double, decimalintlong, float, double, decimaluintlong, ulong, float, double, decimallongfloat, double, decimalulongfloat, double, decimalfloatdoubledouble-decimal-6Explicit ConversionsWide types cant 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 youve warned me about doing this, but Ill take responsibility for what happens.7Examplebyte b;short s = 7;b = s;Console.WriteLine(b = {0}, s = {1}, b, s);8Cannot implicitly convert type short to byte. An explicit conversion exists(are you missing a cast?)Solutionbyte b;short s = 7;b = (byte) s;Console.WriteLine(b = {0}, s = {1}, b, s);9b = 7, s = 7Range Problembyte b;short s = 281;b = (byte) s;Console.WriteLine(b = {0}, s = {1}, b, s);10b = 25, s = 281281 doesnt fit into the byte range!Amount of overflow from 256!Explicit Conversions by ConvertAnother 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.

11A Note on Explicit ConversionsIf 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);12Complex Variable TypesEnumerations (enum)Structures (struct)Arrays13Enumerations (enum)The type double is used to store fractional numbersbool type is used to store true or falseIn real life, there are other existences:Orientation: North, South, East, WestWeek Days: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, SundayMonths: January, February, , DecemberThese types can be implemented by enumerations in C#.14enum SyntaxDefinition:enum { , , }15enum SyntaxDeclaring variables: ;Assigning values: = .;16enum Examplenamespace Ch05Ex02 { enum Orientation { North, South, East, West } class Program { static void Main(string[] args) { Orientation myDirection = Orientation.North; Console.WriteLine("myDirection = {0}", myDirection); } }}17Advanced Topics on enum (1)Each values in an enumeration are stored as integers, starting from 0 and incremented by 1Console.WriteLine("{0} = {1}, {2} = {3}", Orientation.North, (int)Orientation.North, Orientation.South, (int)Orientation.South);18North = 0, South = 1Advanced Topics on enum (2)You can change underlying integer values of some enumerationsUnspecified values are automatically generated by incrementing last valueenum Orientation {North=1, South, East=4, West=8}19North = 1, South = 2,East = 4, West = 8Advanced 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)20StructsStructs 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.)21Defining Structsstruct { ; ; }22Examplestruct Route{ public Orientation Direction; public double Distance;}23Declaring a struct variableSyntax: ;

Example:Route myRoute;myRoute.Orientation = Orientation.North;myRoute.Distance = 2.5;24Exampleroute 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 < 1 || 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);25ArraysUse arrays to store large number of data of same typeint grade1, grade2, grade3, ;int[] grades;Arrays make some operations simpleThink of the case where you want to initialize all values to zero.26Declaring ArraysSyntax:[] ;Example:int[] myIntArray;string[] myStringArray;In this declaration, only a reference without any elements is created27Initializationint[] 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 valuesint[] arr = new int[5] {5, 9, 10, 2, 99};an array of 5 elements with initial valuesint[] 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)28Accessing Array Elementsarr[5] = 10;10 is assigned to the 6th element of the arrayIndexing starts from 0 (not 1)int num = arr[5];6th element of the array is assigned to a variablefor (int i = 0; i < arr.Length; i++){ Console.WriteLine(arr[i]);}All array elements are displayed on the screen.29Examplestring[] 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]);}30Same example with foreachstring[] 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);}31Multidimensional Arraysint[,] 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)32String Operations (1)Concatenationstr = str1 + str2;Accessing a char at specified locationchar ch = str[3]; // 4th element is assigned to chGetting the lengthint size = str.Length;Getting all chars into a char arraychar[] chars = str.ToCharArray();33String Operations (2)Changing to upper or lower casesstr2 = str1.ToUpper();str2 = str1.ToLower();These methods doesnt 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();34String 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); // vanstr2 = str1.SubString(2); // vanced35Split()You can split a string using the Split() methodThe Split() method returns a string arrayIt takes separator chars as a char arrayIf no parameters are supplied, it splits the string according to the white spacesstring str = This is a pencil;string[] arr = str.Split();foreach (string s in arr){ Console.WriteLine(s);}36ThisisapencilUsing 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);}3712345Other String OperationsExamine the following string methods by yourself:CompareTo, EqualsContainsStartsWith, EndsWithIndexOf, IndexOfAny, LastIndexOf, LastIndexOfAnyPadLeft, PadRightRemoveReplace38FunctionsSome tasks may need to be performed at several points in a programe.g. finding the highest number in an arraySolution: Write the code in a function and call it several timesIn object-oriented programming languages, functions of objects are named as methods

39Function Exampleclass Program{ static void DrawBorder() { Console.WriteLine(+--------+); } static void Main(string[] args) { DrawBorder(); Console.WriteLine(| Hello! |); DrawBorder(); }}40+--------+| Hello! |+--------+Dont forget to use the word static!Functions that return a valuestatic 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;}41Functions that take parametersstatic double Product(double a, double b){ return a * b;}42Functions that take array as parameterclass 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); }}43Parameter ArraysIf your function may take variable amount of parameters, then you can use the parameter arraysThink of Console.WriteLine(format, params)You can use any amount of paramete

View more