Reusing Code
Methods
1.Methods
Outline
– What is a Method?
– Why to Use Methods?
– Declaring and Creating Methods
– Calling Methods
– Methods with Parameters
– Passing Parameters
– Returning Values
2. Built in functions
1. Mathematical functions
2. Conversion functions
3. DateTime functions 2
What is a Method?
• A method is a kind of building block that solves a
small problem
– A piece of code that has a name and can be called
from the other code
– Can take parameters and return a value
• Methods allow programmers to construct large
programs from simple pieces
• Methods are also known as functions, procedures,
and subroutines
3
Why to Use Methods?
• More manageable programming
– Split large problems into small
pieces
– Better organization of the program
– Improve code readability
– Improve code understandability
• Avoiding repeating code
Improve code maintainability
• Code reusability
– Using existing methods several
times
4
Calling Methods
• To call a method, simply use:
1. The method’s name
2. Parentheses (don’t forget
them!)
3. A semicolon (;)
PrintLogo();
• This will execute the code in the method’s
body and will result in printing the
following:
IT
Third Year
6
Method Parameters
• To pass information to a method, you can use
parameters (also known as arguments)
– You can pass zero or several input values
– You can pass values of different types
– Each parameter has name and type
– Parameters are assigned to particular values
when the method is called
• Parameters can change the method behavior
depending on the passed values
7
Defining and Using MethodParameters
s t a t i c void PrintSign(int number)
{
i f (number > 0)
MessageBox. Show( "Posi t i ve") ;
else i f (number < 0)
MessageBox. Show( "Negat i ve") ;
else
MessageBox.Show("Zero");
}
Calling
• int num;
• num = Convert.ToInt32(textBox1.Text);
• PrintSign(num);
• Method’s behavior depends on its
parameters
• Parameters can be of any type
– i n t , double, s t r i n g , etc.
– arrays ( i n t [ ] , double[], etc.) 8
Defining and Using Method Parameters
• Methods can have as many parameters as needed:
s t a t i c void PrintMax(float number1, f l o a t number2)
{
f l o a t max = number1; i f
(number2 > number1)
max = number2;
MessageBox.Show(String.Format("Maximal number: { 0 } " , max));
}
Calling:
• float num1,num2;
• num1 = Convert.ToInt32(textBox1.Text);
• num2 = Convert.ToInt32(textBox2.Text);
• PrintMax(num1,num2);
9
Calling Methods with Parameters
• To call a method and pass values
to its parameters:
– Use the method’s name, followed by a list
of expressions for each parameter
• Examples:
PrintSign( -5);
PrintSign(balance);
PrintSign(2+3);
PrintMax(100, 200);
PrintMax(oldQuantity * 1 . 5 , quantity * 2 ) ;
10
Methods Parameters – Example
s t a t i c void PrintSign(int number)
{
i f (number > 0)
MessageBox.ShowString.Format( ("The number {0} i s p o s i t i ve . " ,
number));
else i f (number < 0)
MessageBox.Show(String.Format("The number {0} i s negative.",
number));
else
MessageBox.Show(String.Format("The number {0} i s z e r o . " ,
number));
}
s t a t i c void PrintMax(float number1, f l o a t number2)
{
f l o a t max = number1; i f
(number2 > number1)
{
max = number2;
}
MessageBox.Show(String.Format("Maximal number: { 0 } " , max));
}
reference and value
• You can make changes to the copy and the original will not
be altered. Or you can handle original data. Example:
• private void button1_Click(object sender, EventArgs e)
• {
• int num = 6;
• num += 3;
• addnum(ref num);
• MessageBox.Show(num.ToString()); //displays 16
• }
• void addnum(ref int num)
• {
• num += 7;
• }
• If you do not use ref, the output is 9 because you are dealing
with the copy of the data.
12
Optional Parameters
• C# supports optional parameters with
default values:
s t a t i c void PrintNumber s ( i n t star t = 9 , in t end=10)
{
string r = " " ;
f o r ( i n t i = s t a r t ; i<=end; i + + )
r+=i+"\n";
MessageBox.Show(r);
}
The above method can be called in several ways:
PrintNumbers(5, 1 0 ) ;
PrintNumbers(end:15);
PrintNumbers(); PrintNumber s(end:
40, s t a r t : 35);
13
Defining Methods That Return a Value
• Instead of void, specify the type of data to return
s t a t i c i n t M u l t ip ly( i n t firstNum, i n t secondNum)
{
return firstNum * secondNum;
}
Calling
MessageBox.Show(Multiply(2, 3).ToString());
• Methods can return any type of data ( i n t , s t r i n g , array,
etc.)
• void methods do not return anything
• The combination of method's name, parameters and return
value is called method signature
14
• Use return keyword to return a result
Temperature Conversion – Example
• Convert temperature from Fahrenheit
to Celsius:
s t a t i c double FahrenheitToCelsius(double degrees)
{
double celsius = (degrees - 32) * 5 / 9;
return celsius;
}
private void btnTemprature_Click(object sender, EventArgs e)
{
double t = Double.Parse(textBox1.Text);
t = FahrenheitToCelsius(t);
MessageBox.Show(String.Format("Temperature i n
Celsius: { 0 } " , t ) ) ;
} 15
Square of a number-Example
• int Square( int y )
• {
• return y * y;
• }
• private void btnSquare_Click( object sender,
System.EventArgs e )
• {
• outputLabel.Text = "";
• for ( int counter = 1; counter <= 10; counter++ )
• {
• int result = Square( counter );
• outputLabel.Text += "The square of " + counter + " is " +
result + "\n";
• }
• } 16
Data Validation – Example
• To add class into your project
– Right click on the projects file in the solution
explorer
– Add
– Class
public class ValidatingDemo
{
public s t a t i c bool ValidateMinutes(int minutes)
{
bool result = (minutes>=0) &&(minutes<=59);
return r e s u l t ;
}
public s t a t i c bool ValidateHours(int hours)
{
bool result = (hours>=1) &&(hours<=24);
} return r e s u l t ; 17
}
Data Validation – Example
Calling:
private void button1_Click(object sender, EventArgs e)
{
i n t hours = int.Parse(textBox1.Text);
i n t minutes = int.Parse(textBox2.Text);
bool isValidTime =
ValidatingDemo.ValidateHours(hours) &&
ValidatingDemo.ValidateMinutes(minutes);
i f (isValidTime)
MessageBox.Show(String.Format("It i s
{0}:{1}",hours, minutes));
else
MessageBox.Show("Incorrect t i m e !" ) ;
}
18
Built in functions
• Mathematical
functions
• Conversion functions
• DateTime functions
19
Mathematical
functionsMaximum number
Function
Max
Description
Sqrt Square root
Exp Exponent of ex
Min Minimum number
Abs Absolute value
Log Logarithm
Sin Sine
Tan Tangent
Cos Cosine
Round Rounding
Pow Power of a number
20
Mathematical functions
• Sqrt- is the function that computes the square root of a
number. For example, Math.Sqrt(4)=2, Math.Sqrt(9)=3 etc.
• Abs- is the function that returns the absolute value of a number.
So
Math.Abs(-8) = 8 and Math.Abs(8)= 8.
• Exp- of a number x is the value of ex. For example,
Math.Exp(1)=e1 = 2.7182818284590
• Round- is the function that rounds up a number to a certain
number of decimal places. The Format is Round (n, m) which
means to round a number n to m decimal places. For example,
Math.Round (7.2567, 2) =7.26
• Log- is the function that returns the natural Logarithm of a
number. For example, Math.Log(10, 2), log10 is used to find
natural logarithm.
• Pow. Example: Math.Pow(x,y)xy
• Exercise: 1. use Math.Max to determine the max of 3
numbers
2. Use Math.Min to get minimum of three numbers
21
Conversion functions
• The Implicit operator
• The Explicit operator
• The Iconvertible interface
• The Convert class
• The TypeConverter class-reading
assignment
22
The Implicit operator
• byte byteValue = 16;
• decimal decimalValue;
• decimalValue = byteValue;
• String.Format("After assigning a {0} value, the
Decimal value is {1}.",
byteValue.GetType().Name, decimalValue);
• Output
• After assigning a Byte value, the Decimal
value is 16.
23
Allowed Implicit
Conversion
24
The Explicit conversion
• Use explicit operator. Example:
• 1. uint number1 = int.MaxValue - 1000;
• 2. ulong number1 = int.MaxValue;
• 3. int largeValue = Int32.MaxValue;
• byte newValue;
• newValue = unchecked((byte) largeValue);
• Output: 255
• 4newValue = checked((byte) largeValue);
• Output: outside the range of of byte because the
maximum value of Int32 (largeValue) is 2147483647
which is larger than 255.
25
The IConvertible interface
• This example converts an Int32 value to its equivalent
Char value.
• int codePoint = 65;
• IConvertible iConv = codePoint;
• char ch = iConv.ToChar(null);
• MessageBox.Show(String.Format("Converted {0} to
{1}.", codePoint, ch));
• Output
• A
The Convert class
• int integralValue = 12534;
• decimal decimalValue =
Convert.ToDecimal(integralValue); 26
The Convert class
• TextBox txt=null;
• if (this.ActiveControl is TextBox)
{txt=(TextBox)Convert.ChangeType
(this.ActiveControl, typeof(TextBox));}
txt.Cut();
Parse method
• string value=txtvalue.Text;
• if( value.GetType() == typeof(string) )
• {
• // Parses the string to get the integer to set to the
property.
• int newVal = int.Parse((string)value);
• } 27
DateTime functions
• Add
• AddDays
• AddHours
• AddMinute
s
• AddMonth
s
• AddSecon
ds
• AddYears
• Compare
• Compareto
• Equals 28
DateTime functions
• Add (TimeSpan )
Returns a new DateTime that adds the value of
the specified TimeSpan to the value of this
instance.
Example:
• DateTime value = DateTime.Now;
• TimeSpan span =
value.Subtract(dateTimePicker1.Value);
• value = value.Add(span);
• AddDays ( day )
Returns a new DateTime that adds the specified
number of days to the value of this instance.
Example:
• value.AddDays(1);-Add 1 day to the initial date. 29
DateTime functions
• AddHours ( hour)
Returns a new DateTime that adds the specified
number of hours to the value of this instance.
• Compare ( DateTime t1, DateTime t2)
Compares two instances of DateTime and returns
an integer that indicates whether the first instance
is earlier than, the same as, or later than the
second instance.
– 1 if t1>t2
– -1 if t1<t2
– 0 if t1=t2
• Example;
• DateTime value = DateTime.Now;
• int x = DateTime.Compare(value,
dateTimePicker1.Value);
30
DateTime functions
• CompareTo (DateTime value)
Compares the value of this instance to a specified DateTime
value and returns an integer that indicates whether this
instance is earlier than, the same as, or later than the
specified DateTime value.
Example:
– int x = value.CompareTo(DateTime.Now);
• Equals ( DateTime value)
Returns a value indicating whether the value of this
instance is equal to the value of the specified DateTime
instance. Example:
– bool y = value.Equals(DateTime.Now);
• Equals ( DateTime t1, DateTime t2)
Returns a value indicating whether two DateTime instances
have the same date and time value. Example:
– bool y = DateTime.Equals(value, DateTime.Now);
• ToString
Converts the value of the current DateTime object to its
equivalent string representation. Example: value.ToString(); 31
Namespace
• Reading
• name space and identify:
– The classes under each namesapce
– The properties under each class
– The methods under each class and how
each method is applied.
• Random class
• Recursion
32
Exercises
1. Write a method that asks the user for his name
and prints “Hello, <name>” (for example, “Hello,
Peter!”). Write a program to test this method.
2. Write a method GetMax() with two parameters
that returns the bigger of two integers. Write a
program that reads 3 integers from the console
and prints the biggest of them using the
method GetMax().
3. Write a method that returns the last digit of
given integer as an English word. Examples:
512 "two", 1024 "four", 12309 "nine".
33
Exercises
4. Write a method that counts how many times
given number appears in given array. Write a
test program to check if the method is working
correctly.
5. Write a method that checks if the element at
given position in given array of integers is
bigger than its two neighbors (when such
exist).
6. Write a method that returns the index of the first
element in array that is bigger than its
neighbors, or
-1, if there’s no such element.
– Use the method from the previous exercise.
34
Exercises
7. Write a method that reverses the digits of given decimal
number.
Example: 256 652
8. Write a method that adds two positive integer numbers
represented as arrays of digits (each array element
arr[i] contains a digit; the last digit is kept in a r r [ 0 ] ) .
Each of the numbers that will be added could have up to
10 000 digits.
9. Write a method that return the maximal element in a portion of
array of integers starting at given index. Using it write another
method that sorts an array in ascending / descending order.
35
Exercises
10.Write a program to calculate n ! for each n in
the range [ 1 . . 1 0 0 ] . Hint: Implement first a
method that multiplies a number
represented as array of digits by given
integer number.
11. Extend the program to support also subtraction
and multiplication of polynomials.
36