0% found this document useful (0 votes)
13 views

Chapter 3 Methods

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Chapter 3 Methods

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Reusing Code

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

– 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

Worku K. 4
Declaring and Creating Methods
[static] <return_type> <method_name>([<param_list>])

static void PrintLogo()


Method
{
name
MessageBox.Show(“IT");
MessageBox.Show(“Third Year");
}

• Each method has a name


– It is used to call the method
– Describes its purpose
• The keyword void means that the method does not return
any result
 Each method has a body
 It contains the programming codeSurrounded by { and }
Worku K. 5
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
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);

• Method’s behavior depends on its parameters


• Parameters can be of any type
– int, double, string, etc.
– arrays (int[], double[], etc.)
Worku K. 8
Defining and Using Method Parameters
• Methods can have as many parameters as needed:
static void PrintMax(float number1, float number2)
{
float max = number1;
if (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);
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);
}

The above method can be called in several ways:


PrintNumbers(5, 10);
PrintNumbers(end:15);
PrintNumbers();
PrintNumbers(end: 40, start: 35);
Worku K. 13
Defining Methods That Return a Value
• Instead of void, specify the type of data to return
static int Multiply(int firstNum, int secondNum)
{
return firstNum * secondNum;
}
Calling

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

private void btnTemprature_Click(object sender, EventArgs e)


{
double t = Double.Parse(textBox1.Text);
t = FahrenheitToCelsius(t);
MessageBox.Show(String.Format("Temperature in
Celsius: {0}", t));

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

public static bool ValidateHours(int hours)


{
bool result = (hours>=1) && (hours<=24);
return result;
} Worku K. 17
}
Data Validation – Example
Calling:
private void button1_Click(object sender, EventArgs e)
{

int hours = int.Parse(textBox1.Text);


int minutes = int.Parse(textBox2.Text);
bool isValidTime =
ValidatingDemo.ValidateHours(hours) &&
ValidatingDemo.ValidateMinutes(minutes);
if (isValidTime)
MessageBox.Show(String.Format("It is
{0}:{1}",hours, minutes));
else
MessageBox.Show("Incorrect time!");
}

Worku K. 18
Built in functions
• Mathematical functions
• Conversion functions
• DateTime functions

Worku K. 19
Mathematical functions
Function Description
Max Maximum number

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

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;

• 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.

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

You might also like