Chapter 3 Methods
Chapter 3 Methods
Methods
Outline
1. Methods
– 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
Worku K. 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
Worku K. 3
Why to Use Methods?
• More manageable programming
• Code reusability
Worku K. 4
Declaring and Creating Methods
[static] <return_type> <method_name>([<param_list>])
IT
Third Year
Worku K. 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
Worku K. 7
Defining and Using MethodParameters
static void PrintSign(int number)
{
if (number > 0)
MessageBox.Show("Positive");
else if (number < 0)
MessageBox.Show("Negative");
else
MessageBox.Show("Zero");
}
Calling
• int num;
• num = Convert.ToInt32(textBox1.Text);
• PrintSign(num);
Calling:
• float num1,num2;
• num1 = Convert.ToInt32(textBox1.Text);
• num2 = Convert.ToInt32(textBox2.Text);
• PrintMax(num1,num2);
Worku K. 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);
Worku K. 10
Methods Parameters – Example
static void PrintSign(int number)
{
if (number > 0)
MessageBox.ShowString.Format( ("The number {0} is positive.",
number));
else if (number < 0)
MessageBox.Show(String.Format("The number {0} is negative.",
number));
else
MessageBox.Show(String.Format("The number {0} is zero.",
number));
}
static void PrintMax(float number1, float number2)
{
float max = number1;
if (number2 > number1)
{
max = number2;
}
MessageBox.Show(String.Format("Maximal number: {0}", max));
} Worku K. 11
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.
Worku K. 12
Optional Parameters
• C# supports optional parameters with default
values:
static void PrintNumbers(int start=9, int end=10)
{
string r = "";
for (int i=start; i<=end; i++)
r+=i+"\n";
MessageBox.Show(r);
}
MessageBox.Show(Multiply(2, 3).ToString());
• Methods can return any type of data (int, string, array, etc.)
• void methods do not return anything
• The combination of method's name, parameters and return value
is called method signature
• Use return keyword to return aK.result
Worku 14
Temperature Conversion – Example
• Convert temperature from Fahrenheit to
Celsius:
static double FahrenheitToCelsius(double degrees)
{
double celsius = (degrees - 32) * 5 / 9;
return celsius;
}
} Worku K. 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";
• }
• }
Worku K. 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 static bool ValidateMinutes(int minutes)
{
bool result = (minutes>=0) && (minutes<=59);
return result;
}
Worku K. 18
Built in functions
• Mathematical functions
• Conversion functions
• DateTime functions
Worku K. 19
Mathematical functions
Function Description
Max Maximum number
Worku K. 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
Worku K. 21
Conversion functions
• The Implicit operator
• The Explicit operator
• The Iconvertible interface
• The Convert class
• The TypeConverter class-reading assignment
Worku K. 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.
Worku K. 23
Allowed Implicit Conversion
Worku K. 24
The Explicit conversion
• Use explicit operator. Example:
• 1. uint number1 = int.MaxValue - 1000;
• 2. ulong number1 = int.MaxValue;
Worku K. 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);
Worku K. 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);
• }
Worku K. 27
DateTime functions
• Add
• AddDays
• AddHours
• AddMinutes
• AddMonths
• AddSeconds
• AddYears
• Compare
• Compareto
• Equals
Worku K. 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.
Worku K. 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);
Worku K. 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();
Worku K. 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
Worku K. 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".
Worku K. 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.
Worku K. 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 arr[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.
Worku K. 35
Exercises
10. Write a program to calculate n! for each n in the
range [1..100]. Hint: Implement first a method
that multiplies a number represented as array of
digits by given integer number.
11. Write a method that adds two polynomials.
Represent them as arrays of their coefficients as in
the example below:
x2 + 5 = 1x2 + 0x + 5 5 0 1
12. Extend the program to support also subtraction and
multiplication of polynomials.
Worku K. 36
Exercises
13. Write a program that can solve these tasks:
– Reverses the digits of a number
– Calculates the average of a sequence of integers
– Solves a linear equation a * x + b = 0
Create appropriate methods.
Provide a menu based application for the user to choose
which task to solve.
Validate the input data:
– The decimal number should be non-negative
– The sequence should not be empty
– a should not be equal to 0
Worku K. 37