1) Examples of method (function): Note: the declaration of any method is : <access modifier> <return type> method name ( parameters list ).. Method body.. Access modifier : public,protected, private. Return type : int double,decimal,char,string,bool ( depending on the return variable type ) or void. Method name : a string series of characters. Parameters list : (variable type variable name1, variable type variable name2,..etc) Method body : the process of the method maybe one or more lines of instructions. Example(1): Create a function FindMax that takes two integer values and returns the larger of the two. It has public access specifier, so it can be accessed from outside the class using an instance of the class. Solution: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 public partial class Form1 : Form public Form1() InitializeComponent(); public int FindMax(int num1, int num2) /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; 1
private void button1_click(object sender, EventArgs e) int num1, num2, result; num1 = Convert.ToInt32(textBox1.Text); num2 = Convert.ToInt32(textBox2.Text); result = FindMax(num1, num2); label4.text = result.tostring(); Output : Example (2): Create a windows form C# project that read a student info ( name(string) Address( string ),age ( double) sex( char), marks ( m1,m2,m2,m3) ( double) Then display the result as ( fail/pass), and the average if the students four marks greater than 50. Solution : using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace studentwithoutmethod public partial class Form1 : Form public Form1() InitializeComponent(); private void Form1_Load(object sender, EventArgs e) 2
private void button1_click(object sender, EventArgs e) string name,address,result; char sex; double age,m1,m2,m3,m4,average; //read name name = textbox1.text; //read age as a string then convert to double age = Convert.ToDouble(textBox2.Text); //read address address = textbox3.text; //read sex as striing then convert charcter (f=female m=mail) sex = Convert.ToChar(textBox4.Text); //read mark for four subjects m1 = Convert.ToDouble(textBox5.Text); m2 = Convert.ToDouble(textBox6.Text); m3 = Convert.ToDouble(textBox7.Text); m4 = Convert.ToDouble(textBox8.Text); // check if the student pass or fail if ((m1 > 50) && (m2 > 50) && (m3 > 50) && (m4 > 50)) result = "pass"; average=(m1+m2+m3+m4)/4; textbox10.text=convert.tostring(average); else result="fail"; // display the result textbox9.text =result; private void textbox9_textchanged(object sender, EventArgs e) Output : 1) if the student pass : 3
2)if the student fail : re-write the program : 1)read the values from the program. 2) add method that calculate the average if the student pass the exam. public double calc_average(double m1, double m2, double m3, double m4) return (m1 + m2 + m3+m4) / 4; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace studentwithoutmethod public partial class Form1 : Form public Form1() InitializeComponent(); private void Form1_Load(object sender, EventArgs e) 4
public double calc_average(double m1, double m2, double m3, double m4) return (m1 + m2 + m3+m4) / 4; private void button1_click(object sender, EventArgs e) string name,address,result; char sex; double age,m1,m2,m3,m4,average; //read name name = textbox1.text; //read age as astring then convert todouble age = Convert.ToDouble(textBox2.Text); //read address address = textbox3.text; //read sex as striing conert to charcter (f=female m=mail) sex = Convert.ToChar(textBox4.Text); //read mark for four subjects m1 = Convert.ToDouble(textBox5.Text); m2 = Convert.ToDouble(textBox6.Text); m3 = Convert.ToDouble(textBox7.Text); m4 = Convert.ToDouble(textBox8.Text); // check if the student passor fail if ((m1 >= 50) && (m2 >= 50) && (m3 >= 50) && (m4 >= 50)) result = "pass"; average = calc_average(m1, m2, m3, m4); //average = Average_method(m1, m2,m3,m4); textbox10.text=convert.tostring(average); else result="fail"; // display the result textbox9.text =result; Output: private void textbox9_textchanged(object sender, EventArgs e) 5
Example ( 3) : Method to Calculate the Sum of Prices of Books can use arrays as parameters for a certain method (int[], double[], string[], ). Imagine we are in a bookstore and we want to calculate the amount of money we must pay for all the books we bought. We will create a method that gets the prices of all the books as an array of type decimal[], and then returns the total amount we must pay: public decimal calculate_amountforbooks(decimal[] prices) decimal totalamount = 0; foreach (decimal singlebookprice in prices) totalamount += singlebookprice; return totalamount; solution: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace booksprices 6
public partial class Form1 : Form public Form1() InitializeComponent(); public decimal calculate_amountforbooks(decimal[] prices) decimal totalamount = 0; foreach (decimal singlebookprice in prices) totalamount += singlebookprice; return totalamount; private void button1_click(object sender, EventArgs e) decimal[] pr = 20.5m, 30.60m,1000m; decimal total = calculate_amountforbooks(pr); MessageBox.Show("The total amount for all books is:" +total); Output : example ( 4 ) : overloading 7
Note: When in more than one method is declared and its name is the same but their signatures differ by their parameters list (count of the method s parameters,types of parameters or the way they are arranged), we say that there are different variations / overloads of that method (method overloading). As an example, let s assume that we have to write a program that draws letters and digits to the screen. C# language allows us to create variations of the same method Display( ), called overloads. The method below gets combinations of different parameters, depending of what we want to write on the screen: public void Display(string str) // display string public void Display(int number) // display integer Example(5): Write a program that read a value and check if the value is string or number using method overloading : using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace display public partial class Form1 : Form public Form1() InitializeComponent(); 8
private void Form1_Load(object sender, EventArgs e) public void Display(string str) // display string MessageBox.Show("string "+str); public void Display(int number) // display integer MessageBox.Show("int " ); private void textbox1_textchanged(object sender, EventArgs e) int intnum; if (int.tryparse(textbox1.text, out intnum)) Display(intnum); else Display(textBox1.Text); Output : 9
Exercises 1. Create a method GetMax() with two integer (int) parameters, that returns maximal of the two numbers. 2. Write a program that reads three numbers from the text box and prints the biggest of them. Use the GetMax() method you just created. Write a test program that validates that the works correctly. 3. Write a method that returns the English name of the last digit of a given number. Example: for 512 prints "two"; for 1024 "four". 4. Write a method that finds how many times certain number can be found in a given array. Write a program to test that the method works correctly. 5. Write a method that checks whether an element, from a certain position in an array is greater than its two neighbors. Test whether the method works correctly. 6. Write a method that returns the position of the first occurrence of an element from an array, such that it is greater than its two neighbors simultaneously. Otherwise the result must be -1. 7. 7.Write a method that prints the digits of a given decimal number in a reversed order. For example 256, must be printed as 652. 8. Write a method that calculates the sum of two very positive integer numbers. The numbers are represented as array digits and the last digit (the ones) is stored in the array at index 0. Make the method work for all numbers with length up to 10,000 digits. 9. Write a method that finds the biggest element of an array. Use that method to implement sorting in descending order. 11. Write a program that solves the following tasks: - Put the digits from an integer number into a reversed order. Calculate the average of given sequence of numbers. - Solve the linear equation a * x + b = 0. Create appropriate for each of the above tasks. 10