09. Methods
-
Upload
intro-c-book -
Category
Technology
-
view
35.157 -
download
1
description
Transcript of 09. Methods
MethodsMethodsSubroutines in Computer ProgrammingSubroutines in Computer Programming
Svetlin NakovSvetlin NakovTelerik Telerik
CorporationCorporationwww.telerik.com
Table of ContentsTable of Contents
1.1. Using MethodsUsing Methods What is a Method? Why to Use What is a Method? Why to Use
Methods?Methods? Declaring and Creating MethodsDeclaring and Creating Methods Calling MethodsCalling Methods
2.2. Methods with ParametersMethods with Parameters Passing ParametersPassing Parameters Returning ValuesReturning Values
3.3. Best PracticesBest Practices2
What is a Method?What is a Method? A A methodmethod is a kind of building block is a kind of building block
that solves a small problemthat solves a small problem
A piece of code that has a name and A piece of code that has a name and can be called from the other codecan be called from the other code
Can take parameters and return a Can take parameters and return a valuevalue
Methods allow programmers to Methods allow programmers to construct large programs from simple construct large programs from simple piecespieces
Methods are also known as Methods are also known as functionsfunctions, , proceduresprocedures, and , and subroutinessubroutines 3
Why to Use Methods?Why to Use Methods? More manageable programmingMore manageable programming
Split large problems into small piecesSplit large problems into small pieces Better organization of the programBetter organization of the program Improve code readabilityImprove code readability Improve code understandabilityImprove code understandability
Avoiding repeating codeAvoiding repeating code Improve code maintainabilityImprove code maintainability
Code reusabilityCode reusability Using existing methods several timesUsing existing methods several times
4
Declaring and Declaring and Creating Creating MethodsMethods
Declaring and Creating Declaring and Creating MethodsMethods
Each method has a Each method has a namename It is used to call the methodIt is used to call the method
Describes its purposeDescribes its purpose
static void PrintLogo()static void PrintLogo(){{ Console.WriteLine("Telerik Corp.");Console.WriteLine("Telerik Corp."); Console.WriteLine("www.telerik.com");Console.WriteLine("www.telerik.com");}}
MethMethod od
namename
6
Declaring and Creating Declaring and Creating Methods (2)Methods (2)
Methods declared Methods declared staticstatic can be can be called by any other method (static called by any other method (static or not)or not) This will be discussed later in detailsThis will be discussed later in details
The keyword The keyword voidvoid means that the means that the method does not return any resultmethod does not return any result
static void PrintLogo()static void PrintLogo(){{ Console.WriteLine("Telerik Corp.");Console.WriteLine("Telerik Corp."); Console.WriteLine("www.telerik.com");Console.WriteLine("www.telerik.com");}}
7
static void PrintLogo()static void PrintLogo(){{ Console.WriteLine("Telerik Corp.");Console.WriteLine("Telerik Corp."); Console.WriteLine("www.telerik.com");Console.WriteLine("www.telerik.com");}}
Declaring and Creating Declaring and Creating Methods (3)Methods (3)
Each method has a Each method has a bodybody It contains the programming It contains the programming
codecode Surrounded by Surrounded by {{ and and }}
MethMethod od
bodybody
8
using System;using System;
class MethodExampleclass MethodExample{{ static void PrintLogo()static void PrintLogo() {{ Console.WriteLine("Telerik Corp.");Console.WriteLine("Telerik Corp."); Console.WriteLine("www.telerik.com");Console.WriteLine("www.telerik.com"); }}
static void Main()static void Main() {{ // ...// ... }}} }
Declaring and Creating Declaring and Creating Methods (4)Methods (4)
Methods are always declared inside Methods are always declared inside a a classclass
Main()Main() is also a method like all is also a method like all othersothers
9
Calling MethodsCalling Methods
Calling MethodsCalling Methods To call a method, simply use:To call a method, simply use:
1.1. The method’s nameThe method’s name
2.2. Parentheses (don’t forget them!)Parentheses (don’t forget them!)
3.3. A semicolon (A semicolon (;;))
This will execute the code in the This will execute the code in the method’s body and will result in method’s body and will result in printing the following:printing the following:
PrintLogo();PrintLogo();
Telerik Corp.Telerik Corp.www.telerik.comwww.telerik.com
11
Calling Methods (2)Calling Methods (2) A method can be called from:A method can be called from:
TheThe Main()Main() method method
Any other methodAny other method
Itself (process known as Itself (process known as recursionrecursion))
static void Main()static void Main(){{ // ...// ... PrintLogo();PrintLogo(); // ...// ...}}
12
Declaring and Declaring and Calling Calling
MethodsMethodsLive DemoLive Demo
Methods with Methods with ParametersParametersPassing Parameters and Returning Passing Parameters and Returning
ValuesValues
Method ParametersMethod Parameters To pass information to a method, you can To pass information to a method, you can
use use parameters parameters (also known as (also known as argumentsarguments))
You can pass zero or several input valuesYou can pass zero or several input values
You can pass values of different typesYou can pass values of different types
Each parameter has name and typeEach parameter has name and type
Parameters are assigned to particular Parameters are assigned to particular values when the method is calledvalues when the method is called
Parameters can change the method Parameters can change the method behavior depending on the passed valuesbehavior depending on the passed values
15
Defining and Using Defining and Using Method ParametersMethod Parameters
Method’s behavior depends on its Method’s behavior depends on its parametersparameters
Parameters can be of any typeParameters can be of any type intint, , doubledouble, , stringstring, etc., etc. arrays (arrays (intint[][], , double[]double[], etc.), etc.)
static void PrintSign(int number)static void PrintSign(int number){{ if (number > 0)if (number > 0) Console.WriteLine("Positive");Console.WriteLine("Positive"); else if (number < 0)else if (number < 0) Console.WriteLine("Negative");Console.WriteLine("Negative"); elseelse Console.WriteLine("Zero");Console.WriteLine("Zero");}}
16
Defining and Using Defining and Using Method Parameters (2)Method Parameters (2)
Methods can have as many Methods can have as many parameters as needed:parameters as needed:
The following syntax is not valid:The following syntax is not valid:
static void PrintMax(float number1, float number2)static void PrintMax(float number1, float number2)
{{
float max = number1;float max = number1;
if (number2 > number1)if (number2 > number1)
max = number2;max = number2;
Console.WriteLine("Maximal number: {0}", max);Console.WriteLine("Maximal number: {0}", max);
}}
static void PrintMax(float number1, number2)static void PrintMax(float number1, number2)
17
Calling MethodsCalling Methodswith Parameterswith Parameters
To call a method and pass values To call a method and pass values to its parameters:to its parameters: Use the method’s name, followed by Use the method’s name, followed by
a list of expressions for each a list of expressions for each parameterparameter
Examples:Examples:PrintSign(-5);PrintSign(-5);PrintSign(balance);PrintSign(balance);PrintSign(2+3);PrintSign(2+3);
PrintMax(100, 200);PrintMax(100, 200);PrintMax(oldQuantity * 1.5, quantity * 2);PrintMax(oldQuantity * 1.5, quantity * 2);
18
Calling MethodsCalling Methodswith Parameters (2)with Parameters (2)
Expressions must be of the same Expressions must be of the same type as method’s parameters (or type as method’s parameters (or compatible)compatible)
If the method requires a If the method requires a floatfloat expression, you can pass expression, you can pass intint instead instead
Use the same order like in method Use the same order like in method declarationdeclaration
For methods with no parameters do For methods with no parameters do not forget the parenthesesnot forget the parentheses
19
ExamplesExamples
Using Using Methods Methods
With With ParametersParameters
Methods Parameters – Methods Parameters – ExampleExample
static void PrintSign(int number)static void PrintSign(int number){{ if (number > 0)if (number > 0) Console.WriteLine("The number {0} is positive.", Console.WriteLine("The number {0} is positive.", number);number); else if (number < 0)else if (number < 0) Console.WriteLine("The number {0} is negative.", Console.WriteLine("The number {0} is negative.", number);number); elseelse Console.WriteLine("The number {0} is zero.", Console.WriteLine("The number {0} is zero.", number);number);}}
static void PrintMax(float number1, float number2)static void PrintMax(float number1, float number2){{ float max = number1;float max = number1; if (number2 > number1)if (number2 > number1) {{ max = number2;max = number2; }} Console.WriteLine("Maximal number: {0}", max);Console.WriteLine("Maximal number: {0}", max);}}
21
Live DemoLive Demo
Method ParametersMethod Parameters
Months – ExampleMonths – Example
Display the period between two Display the period between two months in a user-friendly waymonths in a user-friendly wayusing System;using System;
class MonthsExampleclass MonthsExample{{ static void SayMonth(int month)static void SayMonth(int month) {{ string[] monthNames = new string[] {string[] monthNames = new string[] { "January", "February", "March", "January", "February", "March", "April", "May", "June", "July", "April", "May", "June", "July", "August", "September", "October","August", "September", "October", "November", "December"};"November", "December"}; Console.Write(monthNames[month-1]);Console.Write(monthNames[month-1]); }}
(the example continues)(the example continues)
23
Months – Example (2)Months – Example (2)
static void SayPeriod(int startMonth, int endMonth)static void SayPeriod(int startMonth, int endMonth)
{{
int period = endMonth - startMonth;int period = endMonth - startMonth;
if (period < 0)if (period < 0)
{{
period = period + 12;period = period + 12;
// From December to January the// From December to January the
// period is 1 month, not -11!// period is 1 month, not -11!
}}
Console.Write("There are {0} " + months from ", Console.Write("There are {0} " + months from ",
period);period);
SayMonth(startMonth);SayMonth(startMonth);
Console.Write(" to ");Console.Write(" to ");
SayMonth(endMonth);SayMonth(endMonth);
}}
}}24
Live DemoLive Demo
MonthMonthss
Printing Triangle – Printing Triangle – ExampleExample
Creating a program for printing Creating a program for printing triangles as shown below:triangles as shown below:
1111 1 21 21 21 2 1 2 31 2 31 2 31 2 3 1 2 3 41 2 3 41 2 3 41 2 3 4 1 2 3 4 51 2 3 4 5
n=5 n=5 1 2 3 4 51 2 3 4 5 n=6 n=6 1 2 3 1 2 3 4 5 64 5 61 2 3 41 2 3 4 1 2 3 4 51 2 3 4 51 2 31 2 3 1 2 3 41 2 3 41 21 2 1 2 31 2 311 1 21 2
1 1 26
Printing Triangle – Printing Triangle – ExampleExample
static void Main()static void Main(){{ int n = int.Parse(Console.ReadLine());int n = int.Parse(Console.ReadLine());
for (int line = 1; line <= n; line++)for (int line = 1; line <= n; line++) PrintLine(1, line);PrintLine(1, line); for (int line = n-1; line >= 1; line--)for (int line = n-1; line >= 1; line--) PrintLine(1, line);PrintLine(1, line);}}
static void PrintLine(int start, int end)static void PrintLine(int start, int end){{ for (int i = start; i <= end; i++)for (int i = start; i <= end; i++) {{ Console.Write(" {0}", i);Console.Write(" {0}", i); }} Console.WriteLine();Console.WriteLine();}}
27
Printing TrianglePrinting TriangleLive DemoLive Demo
Optional ParametersOptional Parameters C# 4.0 supports optional parameters C# 4.0 supports optional parameters
with default values:with default values:
The above method can be called in The above method can be called in several ways:several ways:
static void PrintNumbers(int start=0; int end=100){{ for (int i=start; i<=end; i++)for (int i=start; i<=end; i++) {{ Console.Write("{0} ", i);Console.Write("{0} ", i); }}}}
PrintNumbers(5, 10);PrintNumbers(15);PrintNumbers();PrintNumbers(end: 40, start: 35);
29
Optional ParametersOptional ParametersLive DemoLive Demo
Returning Returning Values From Values From
MethodsMethods
Returning Values From Returning Values From MethodsMethods
A method can A method can returnreturn a value to its a value to its callercaller
Returned value:Returned value: Can be assigned to a variable:Can be assigned to a variable:
Can be used in expressions:Can be used in expressions:
Can be passed to another method:Can be passed to another method:
string message = Console.ReadLine();string message = Console.ReadLine();// Console.ReadLine() returns a string// Console.ReadLine() returns a string
float price = GetPrice() * quantity * 1.20;float price = GetPrice() * quantity * 1.20;
int age = int.Parse(Console.ReadLine());int age = int.Parse(Console.ReadLine());
32
Defining Defining Methods That Methods That
Return a ValueReturn a Value Instead of Instead of voidvoid, specify the type of data to , specify the type of data to
returnreturn
Methods can return any type of data (Methods can return any type of data (intint, , stringstring, array, etc.), array, etc.)
voidvoid methods do not return anything methods do not return anything The combination of method's name, The combination of method's name,
parameters and return value is called parameters and return value is called method signaturemethod signature
Use Use returnreturn keyword to return a result keyword to return a result
static int Multiply(int firstNum, int secondNum)static int Multiply(int firstNum, int secondNum){{ return firstNum * secondNum;return firstNum * secondNum;}}
33
The The returnreturn Statement Statement
The The returnreturn statement: statement: Immediately terminates method’s Immediately terminates method’s
executionexecution
Returns specified expression to the callerReturns specified expression to the caller
Example:Example:
To terminate To terminate voidvoid method, use just: method, use just:
Return can be used several times in a Return can be used several times in a method bodymethod body
return -1;
return;
34
ExamplesExamples
Returning Returning Values From Values From
MethodsMethods
ExamplesExamples
Returning Returning Values From Values From
MethodsMethods
Temperature Temperature Conversion – Conversion –
ExampleExample Convert temperature from Convert temperature from
Fahrenheit to Celsius:Fahrenheit to Celsius:static double FahrenheitToCelsius(double degrees)static double FahrenheitToCelsius(double degrees){{ double celsius = (degrees - 32) * 5 / 9;double celsius = (degrees - 32) * 5 / 9; return celsius;return celsius;}}
static void Main()static void Main(){{ Console.Write("Temperature in Fahrenheit: ");Console.Write("Temperature in Fahrenheit: "); double t = Double.Parse(Console.ReadLine());double t = Double.Parse(Console.ReadLine()); t = FahrenheitToCelsius(t);t = FahrenheitToCelsius(t); Console.Write("Temperature in Celsius: {0}", t);Console.Write("Temperature in Celsius: {0}", t);}}
37
Live DemoLive Demo
Temperature Temperature ConversionConversion
Positive Numbers – Positive Numbers – ExampleExample
Check if all numbers in a sequence Check if all numbers in a sequence are positive:are positive:
static bool ArePositive(int[] sequence)static bool ArePositive(int[] sequence){{ foreach (int number in sequence)foreach (int number in sequence) {{ if (number <= 0)if (number <= 0) {{ return false;return false; }} }} return true;return true;}}
39
Live DemoLive Demo
Positive Positive NumbersNumbers
Data Validation – Data Validation – ExampleExample
Validating input data:Validating input data:using System;using System;
class ValidatingDemoclass ValidatingDemo{{ static void Main()static void Main() {{ Console.WriteLine("What time is it?");Console.WriteLine("What time is it?"); Console.Write("Hours: ");Console.Write("Hours: "); int hours = int.Parse(Console.ReadLine());int hours = int.Parse(Console.ReadLine());
Console.Write("Minutes: ");Console.Write("Minutes: "); int minutes = int.Parse(Console.ReadLine());int minutes = int.Parse(Console.ReadLine());
// (The example continues on the next slide)// (The example continues on the next slide)
41
Data Validation – Data Validation – ExampleExample
bool isValidTime = bool isValidTime = ValidateHours(hours) &&ValidateHours(hours) && ValidateMinutes(minutes);ValidateMinutes(minutes); if (isValidTime)if (isValidTime) Console.WriteLine("It is {0}:{1}",Console.WriteLine("It is {0}:{1}", hours, minutes);hours, minutes); elseelse Console.WriteLine("Incorrect time!");Console.WriteLine("Incorrect time!"); }}
static bool ValidateMinutes(int minutes)static bool ValidateMinutes(int minutes) {{ bool result = (minutes>=0) && (minutes<=59);bool result = (minutes>=0) && (minutes<=59); return result;return result; }}
static bool ValidateHours(int hours) { ... }static bool ValidateHours(int hours) { ... }}}
42
Live DemoLive Demo
Data Data ValidationValidation
Methods – Best Methods – Best PracticesPractices
Each method should perform a single,Each method should perform a single, well-defined task well-defined task
Method’s name should describe that Method’s name should describe that task in a clear and non-ambiguous waytask in a clear and non-ambiguous way Good examples: Good examples: CalculatePriceCalculatePrice, , ReadNameReadName
Bad examples: Bad examples: ff, , g1g1, , ProcessProcess
In C# methods should start with capital In C# methods should start with capital letterletter
Avoid methods longer than one screenAvoid methods longer than one screen Split them to several shorter methodsSplit them to several shorter methods
44
SummarySummary Break large programs into simple Break large programs into simple
methods that solve small sub-methods that solve small sub-problemsproblems
Methods consist of declaration and Methods consist of declaration and bodybody
Methods are invoked by their nameMethods are invoked by their name Methods can accept parametersMethods can accept parameters
Parameters take actual values when Parameters take actual values when calling a methodcalling a method
Methods can return a value or Methods can return a value or nothingnothing
45
QuestionsQuestions??
MethodsMethods
http://academy.telerik.com
ExercisesExercises
1.1. Write a method that asks the user for his Write a method that asks the user for his name and prints “Hello, <name>” (for name and prints “Hello, <name>” (for example, “Hello, Peter!”). Write a program example, “Hello, Peter!”). Write a program to test this method.to test this method.
2.2. Write a method Write a method GetMax()GetMax() with two with two parameters that returns the bigger of two parameters that returns the bigger of two integers. Write a program that reads 3 integers. Write a program that reads 3 integers from the console and prints the integers from the console and prints the biggest of them using the method biggest of them using the method GetMax()GetMax()..
3.3. Write a method that returns the last digit of Write a method that returns the last digit of given integer as an English word. Examples: given integer as an English word. Examples: 512 512 "two", 1024 "two", 1024 "four", 12309 "four", 12309 "nine". "nine".
47
Exercises (2)Exercises (2)
4.4. Write a method that counts how many times Write a method that counts how many times given number appears in given array. Write given number appears in given array. Write a test program to check if the method is a test program to check if the method is working correctly.working correctly.
5.5. Write a method that checks if the element at Write a method that checks if the element at given position in given array of integers is given position in given array of integers is bigger than its two neighbors (when such bigger than its two neighbors (when such exist).exist).
6.6. Write a method that returns the index of the Write a method that returns the index of the first element in array that is bigger than its first element in array that is bigger than its neighbors, or -1, if there’s no such element.neighbors, or -1, if there’s no such element.
Use the method from the previous exercise.Use the method from the previous exercise.48
Exercises (3)Exercises (3)
7.7. Write a method that reverses the digits of Write a method that reverses the digits of given decimal number. Example: 256 given decimal number. Example: 256 652 652
8.8. Write a method that adds two positive integer Write a method that adds two positive integer numbers represented as arrays of digits (each numbers represented as arrays of digits (each array element array element arr[iarr[i]] contains a digit; the last contains a digit; the last digit is kept in digit is kept in arr[0]arr[0]). Each of the numbers ). Each of the numbers that will be added could have up to 10 000 that will be added could have up to 10 000 digits.digits.
9.9. Write a method that return the maximal Write a method that return the maximal element in a portion of array of integers element in a portion of array of integers starting at given index. Using it write another starting at given index. Using it write another method that sorts an array in ascending / method that sorts an array in ascending / descending order.descending order.
49
Exercises (4)Exercises (4)
10.10. Write a program to calculate Write a program to calculate n!n! for each for each nn in in the range the range [1..100][1..100]. Hint: Implement first a . Hint: Implement first a method that multiplies a number method that multiplies a number represented as array of digits by given represented as array of digits by given integer number. integer number.
11.11. Write a method that adds two polynomials. Write a method that adds two polynomials. Represent them as arrays of their Represent them as arrays of their coefficients as in the example below:coefficients as in the example below:
xx22 + 5 = 1 + 5 = 1xx22 + 0 + 0xx + 5 + 5
10.10. Extend the program to support also Extend the program to support also subtraction and multiplication of subtraction and multiplication of polynomials.polynomials.
55 00 11
50
Exercises (5)Exercises (5)13.13. Write a program that can solve these Write a program that can solve these
tasks:tasks: Reverses the digits of a numberReverses the digits of a number
Calculates the average of a sequence of Calculates the average of a sequence of integersintegers
Solves a linear equation Solves a linear equation aa * * xx + + bb = 0 = 0
Create appropriate methods.Create appropriate methods.
Provide a simple text-based menu for Provide a simple text-based menu for the user to choose which task to solve.the user to choose which task to solve.
Validate the input data:Validate the input data: The decimal number should be non-negativeThe decimal number should be non-negative
The sequence should not be emptyThe sequence should not be empty
aa should not be equal to should not be equal to 00 51