Presentation is loading. Please wait.

Presentation is loading. Please wait.

BİL527 – Bilgisayar Programlama I Functions 1. Contents Functions Delegates 2.

Similar presentations


Presentation on theme: "BİL527 – Bilgisayar Programlama I Functions 1. Contents Functions Delegates 2."— Presentation transcript:

1 BİL527 – Bilgisayar Programlama I Functions 1

2 Contents Functions Delegates 2

3 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 3

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

5 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; } 5

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

7 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); } 7

8 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 8

9 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); } 9

10 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 10

11 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); } 11 val doubled = 10 myNumber in main: 5

12 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); } 12 1 2 3 4 5 99 2 3 4 5

13 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) 13

14 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); } 14 val doubled = 10 myNumber in main: 10

15 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); } 15

16 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; } 16

17 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 17

18 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) 18

19 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); } 19

20 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 20

21 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” 21

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

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

24 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 24

25 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); } 25

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

27 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 27

28 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; } 28 Declaration

29 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)); } 29

30 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)); } 30


Download ppt "BİL527 – Bilgisayar Programlama I Functions 1. Contents Functions Delegates 2."

Similar presentations


Ads by Google