SlideShare a Scribd company logo
MethodsMethods
Subroutines in Computer ProgrammingSubroutines in Computer Programming
Svetlin NakovSvetlin Nakov
Telerik CorporationTelerik Corporation
www.telerik.comwww.telerik.com
Table of ContentsTable of Contents
1.1. Using MethodsUsing Methods
 What is a Method? Why to Use Methods?What is a Method? Why to Use Methods?
 Declaring and Creating MethodsDeclaring and Creating Methods
 Calling MethodsCalling Methods
1.1. Methods with ParametersMethods with Parameters
 Passing ParametersPassing Parameters
 Returning ValuesReturning Values
1.1. Best PracticesBest Practices
2
What is a Method?What is a Method?
 AA methodmethod is a kind of building block that solvesis a kind of building block that solves
a small problema small problem
A piece of code that has a name and can beA piece of code that has a name and can be
called from the other codecalled from the other code
Can take parameters and return a valueCan take parameters and return a value
 Methods allow programmers to construct largeMethods allow programmers to construct large
programs from simple piecesprograms from simple pieces
 Methods are also known asMethods 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 andDeclaring and
Creating MethodsCreating Methods
Declaring and Creating MethodsDeclaring and Creating Methods
 Each method has aEach 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");
}}
MethodMethod
namename
6
Declaring and Creating Methods (2)Declaring and Creating Methods (2)
 Methods declaredMethods declared staticstatic can be called bycan be called by
any other method (static or not)any other method (static or not)
This will be discussed later in detailsThis will be discussed later in details
 The keywordThe keyword voidvoid means that the methodmeans that the method
does not return any resultdoes 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 Methods (3)Declaring and Creating Methods (3)
 Each method has aEach method has a bodybody
 It contains the programming codeIt contains the programming code
 Surrounded bySurrounded by {{ andand }}
MethodMethod
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 Methods (4)Declaring and Creating Methods (4)
 Methods are always declared inside aMethods are always declared inside a classclass
 Main()Main() is also a method like all othersis also a method like all others
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 method’sThis will execute the code in the method’s
body and will result in printing the following:body and will result in 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() methodmethod
Any other methodAny other method
Itself (process known asItself (process known as recursionrecursion))
static void Main()static void Main()
{{
// ...// ...
PrintLogo();PrintLogo();
// ...// ...
}}
12
Declaring andDeclaring and
Calling MethodsCalling Methods
Live DemoLive Demo
Methods with ParametersMethods with Parameters
Passing Parameters and Returning ValuesPassing Parameters and Returning Values
Method ParametersMethod Parameters
 To pass information to a method, you can useTo pass information to a method, you can use
parametersparameters (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 valuesParameters are assigned to particular values
when the method is calledwhen the method is called
 Parameters can change the method behaviorParameters can change the method behavior
depending on the passed valuesdepending on the passed values
15
Defining and UsingDefining and Using
Method ParametersMethod Parameters
 Method’s behavior depends on its parametersMethod’s behavior depends on its parameters
 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 UsingDefining and Using
Method Parameters (2)Method Parameters (2)
 Methods can have as many parameters asMethods can have as many parameters as
needed: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 Methods
with Parameterswith Parameters
 To call a method and pass values to itsTo call a method and pass values to its
parameters:parameters:
Use the method’s name, followed by a list ofUse the method’s name, followed by a list of
expressions for each parameterexpressions for each parameter
 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 Methods
with Parameters (2)with Parameters (2)
 Expressions must be of the same type asExpressions must be of the same type as
method’s parameters (or compatible)method’s parameters (or compatible)
If the method requires aIf the method requires a floatfloat expression, youexpression, you
can passcan pass intint insteadinstead
 Use the same order like in method declarationUse the same order like in method declaration
 For methods with no parameters do not forgetFor methods with no parameters do not forget
the parenthesesthe parentheses
19
ExamplesExamples
Using MethodsUsing Methods
With ParametersWith Parameters
Methods Parameters – ExampleMethods Parameters – Example
static void PrintSign(int number)static void PrintSign(int number)
{{
if (number > 0)if (number > 0)
Console.WriteLine("The number {0} is positive.", number);Console.WriteLine("The number {0} is positive.", number);
else if (number < 0)else if (number < 0)
Console.WriteLine("The number {0} is negative.", number);Console.WriteLine("The number {0} is negative.", number);
elseelse
Console.WriteLine("The number {0} is zero.", number);Console.WriteLine("The number {0} is zero.", 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 months in aDisplay the period between two months in a
user-friendly wayuser-friendly way
using 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 ", period);Console.Write("There are {0} " + months from ", period);
SayMonth(startMonth);SayMonth(startMonth);
Console.Write(" to ");Console.Write(" to ");
SayMonth(endMonth);SayMonth(endMonth);
}}
}}
24
Live DemoLive Demo
MonthsMonths
Printing Triangle – ExamplePrinting Triangle – Example
 Creating a program for printing triangles asCreating a program for printing triangles as
shown below:shown below:
11
11 1 21 2
1 21 2 1 2 31 2 3
1 2 31 2 3 1 2 3 41 2 3 4
1 2 3 41 2 3 4 1 2 3 4 51 2 3 4 5
n=5n=5  1 2 3 4 51 2 3 4 5 n=6n=6  1 2 3 4 5 61 2 3 4 5 6
1 2 3 41 2 3 4 1 2 3 4 51 2 3 4 5
1 2 31 2 3 1 2 3 41 2 3 4
1 21 2 1 2 31 2 3
11 1 21 2
11
26
Printing Triangle – ExamplePrinting Triangle – Example
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
PrintingTrianglePrintingTriangle
Live DemoLive Demo
Optional ParametersOptional Parameters
 C# 4.0 supports optional parameters with defaultC# 4.0 supports optional parameters with default
values:values:
 The above method can be called in several ways:The above method can be called in 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 Parameters
Live DemoLive Demo
ReturningValuesReturningValues
From MethodsFrom Methods
Returning Values From MethodsReturning Values From Methods
 A method canA method can returnreturn a value to its callera value to its caller
 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 MethodsDefining Methods
That Return a ValueThat Return a Value
 Instead ofInstead of voidvoid, specify the type of data to return, specify the type of data to return
 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 anythingmethods do not return anything
 The combination of method's name, parametersThe combination of method's name, parameters
and return value is calledand return value is called method signaturemethod signature
 UseUse returnreturn keyword to return a resultkeyword 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
TheThe returnreturn StatementStatement
 TheThe returnreturn statement:statement:
Immediately terminates method’s executionImmediately terminates method’s execution
Returns specified expression to the callerReturns specified expression to the caller
Example:Example:
 To terminateTo terminate voidvoid method, use just:method, use just:
 Return can be used several times in a methodReturn can be used several times in a method
bodybody
return -1;
return;
34
ExamplesExamples
ReturningValuesReturningValues
From MethodsFrom Methods
ExamplesExamples
ReturningValuesReturningValues
From MethodsFrom Methods
TemperatureTemperature
Conversion – ExampleConversion – Example
 Convert temperature from Fahrenheit toConvert temperature from Fahrenheit to
Celsius: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 ConversionTemperature Conversion
Positive Numbers – ExamplePositive Numbers – Example
 Check if all numbers in a sequence are positive:Check if all numbers in a sequence 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 NumbersPositive Numbers
Data Validation – ExampleData Validation – Example
 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 – ExampleData Validation – Example
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
DataValidationDataValidation
Methods – Best PracticesMethods – Best Practices
 Each method should perform a single,Each method should perform a single,
well-defined taskwell-defined task
 Method’s name should describe thatMethod’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 letterIn C# methods should start with capital letter
 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 methodsBreak large programs into simple methods
that solve small sub-problemsthat solve small sub-problems
 Methods consist of declaration and bodyMethods consist of declaration and body
 Methods are invoked by their nameMethods are invoked by their name
 Methods can accept parametersMethods can accept parameters
 Parameters take actual values when calling aParameters take actual values when calling a
methodmethod
 Methods can return a value or nothingMethods can return a value or nothing
45
Questions?Questions?
MethodsMethods
http://academy.telerik.com
ExercisesExercises
1.1. Write a method that asks the user for his name andWrite a method that asks the user for his name and
prints “Hello, <name>” (for example, “Hello,prints “Hello, <name>” (for example, “Hello,
Peter!”). Write a program to test this method.Peter!”). Write a program to test this method.
2.2. Write a methodWrite a method GetMax()GetMax() with two parameters thatwith two parameters that
returns the bigger of two integers. Write a programreturns the bigger of two integers. Write a program
that reads 3 integers from the console and prints thethat reads 3 integers from the console and prints the
biggest of them using the methodbiggest of them using the method GetMax()GetMax()..
3.3. Write a method that returns the last digit of givenWrite a method that returns the last digit of given
integer as an English word. Examples: 512integer as an English word. Examples: 512  "two","two",
10241024  "four", 12309"four", 12309  "nine"."nine".
47
Exercises (2)Exercises (2)
4.4. Write a method that counts how many times givenWrite a method that counts how many times given
number appears in given array. Write a test programnumber appears in given array. Write a test program
to check if the method is working correctly.to check if the method is working correctly.
5.5. Write a method that checks if the element at givenWrite a method that checks if the element at given
position in given array of integers is bigger than itsposition in given array of integers is bigger than its
two neighbors (when such exist).two neighbors (when such exist).
6.6. Write a method that returns the index of the firstWrite a method that returns the index of the first
element in array that is bigger than its neighbors, orelement in array that is bigger than its neighbors, or
-1, if there’s no such element.-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 givenWrite a method that reverses the digits of given
decimal number. Example: 256decimal number. Example: 256  652652
8.8. Write a method that adds two positive integerWrite a method that adds two positive integer
numbers represented as arrays of digits (each arraynumbers represented as arrays of digits (each array
elementelement arr[iarr[i]] contains a digit; the last digit iscontains a digit; the last digit is
kept inkept in arr[0]arr[0]). Each of the numbers that will be). Each of the numbers that will be
added could have up to 10 000 digits.added could have up to 10 000 digits.
9.9. Write a method that return the maximal element inWrite a method that return the maximal element in
a portion of array of integers starting at given index.a portion of array of integers starting at given index.
Using it write another method that sorts an array inUsing it write another method that sorts an array in
ascending / descending order.ascending / descending order.
49
Exercises (4)Exercises (4)
10.10. Write a program to calculateWrite a program to calculate n!n! for eachfor each nn in thein the
rangerange [1..100][1..100]. Hint: Implement first a method. Hint: Implement first a method
that multiplies a number represented as array ofthat multiplies a number represented as array of
digits by given integer number.digits by given integer number.
11.11. Write a method that adds two polynomials.Write a method that adds two polynomials.
Represent them as arrays of their coefficients as inRepresent them as arrays of their coefficients as in
the example below:the example below:
xx22
+ 5 = 1+ 5 = 1xx22
+ 0+ 0xx + 5+ 5 
10.10. Extend the program to support also subtraction andExtend the program to support also subtraction and
multiplication of polynomials.multiplication of polynomials.
55 00 11
50
Exercises (5)Exercises (5)
13.13. Write a program that can solve these tasks:Write a program that can solve these tasks:
 Reverses the digits of a numberReverses the digits of a number
 Calculates the average of a sequence of integersCalculates the average of a sequence of integers
 Solves a linear equationSolves a linear equation aa ** xx ++ bb = 0= 0
Create appropriate methods.Create appropriate methods.
Provide a simple text-based menu for the user toProvide a simple text-based menu for the user to
choose which task to solve.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 toshould not be equal to 00
51

More Related Content

What's hot

10. Recursion
10. Recursion10. Recursion
10. Recursion
Intro C# Book
 
C Programming Language
C Programming LanguageC Programming Language
C Programming Language
RTS Tech
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
Anton Bikineev
 
conditional statements
conditional statementsconditional statements
conditional statements
James Brotsos
 
04. Console Input Output
04. Console Input Output 04. Console Input Output
04. Console Input Output
Intro C# Book
 
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17
OdessaFrontend
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
RTS Tech
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional Statements
Intro C# Book
 
45 aop-programming
45 aop-programming45 aop-programming
45 aop-programmingdaotuan85
 
Unit iii
Unit iiiUnit iii
Unit iii
snehaarao19
 
16 -ansi-iso_standards
16  -ansi-iso_standards16  -ansi-iso_standards
16 -ansi-iso_standardsHector Garzo
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
Rasan Samarasinghe
 
C tutorial
C tutorialC tutorial
C tutorial
Anurag Sukhija
 
Python-oop
Python-oopPython-oop
Python-oop
RTS Tech
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
Rasan Samarasinghe
 

What's hot (19)

C tutorial
C tutorialC tutorial
C tutorial
 
10. Recursion
10. Recursion10. Recursion
10. Recursion
 
C Programming Language
C Programming LanguageC Programming Language
C Programming Language
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
 
conditional statements
conditional statementsconditional statements
conditional statements
 
Lec 10
Lec 10Lec 10
Lec 10
 
Cheat Sheet java
Cheat Sheet javaCheat Sheet java
Cheat Sheet java
 
04. Console Input Output
04. Console Input Output 04. Console Input Output
04. Console Input Output
 
1
11
1
 
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional Statements
 
45 aop-programming
45 aop-programming45 aop-programming
45 aop-programming
 
Unit iii
Unit iiiUnit iii
Unit iii
 
16 -ansi-iso_standards
16  -ansi-iso_standards16  -ansi-iso_standards
16 -ansi-iso_standards
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
C tutorial
C tutorialC tutorial
C tutorial
 
Python-oop
Python-oopPython-oop
Python-oop
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 

Viewers also liked

18 Hash tables and sets
18 Hash tables and sets18 Hash tables and sets
18 Hash tables and sets
maznabili
 
21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii
maznabili
 
00 Fundamentals of csharp course introduction
00 Fundamentals of csharp course introduction00 Fundamentals of csharp course introduction
00 Fundamentals of csharp course introduction
maznabili
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
maznabili
 
Everything You know about CSS is Wrong
Everything You know about CSS is WrongEverything You know about CSS is Wrong
Everything You know about CSS is Wrong
chandleryu
 
22 Methodology of problem solving
22 Methodology of problem solving22 Methodology of problem solving
22 Methodology of problem solving
maznabili
 
04 Console input output-
04 Console input output-04 Console input output-
04 Console input output-
maznabili
 
Creating a CSS layout from scratch
Creating a CSS layout from scratchCreating a CSS layout from scratch
Creating a CSS layout from scratch
Designveloper
 
Floating
FloatingFloating
Floating
Danielle Larson
 
Steps for CSS Layout
Steps for CSS LayoutSteps for CSS Layout
Steps for CSS Layout
Alexander Sperl
 
12 Exceptions handling
12 Exceptions handling12 Exceptions handling
12 Exceptions handling
maznabili
 
08 Numeral systems
08 Numeral systems08 Numeral systems
08 Numeral systems
maznabili
 
03 Operators and expressions
03 Operators and expressions03 Operators and expressions
03 Operators and expressions
maznabili
 
15 Text files
15 Text files15 Text files
15 Text files
maznabili
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statements
maznabili
 
19 Algorithms and complexity
19 Algorithms and complexity19 Algorithms and complexity
19 Algorithms and complexity
maznabili
 
01 Introduction to programming
01 Introduction to programming01 Introduction to programming
01 Introduction to programming
maznabili
 

Viewers also liked (20)

18 Hash tables and sets
18 Hash tables and sets18 Hash tables and sets
18 Hash tables and sets
 
21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii
 
00 Fundamentals of csharp course introduction
00 Fundamentals of csharp course introduction00 Fundamentals of csharp course introduction
00 Fundamentals of csharp course introduction
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
 
Layout
LayoutLayout
Layout
 
Css advance
Css   advanceCss   advance
Css advance
 
Everything You know about CSS is Wrong
Everything You know about CSS is WrongEverything You know about CSS is Wrong
Everything You know about CSS is Wrong
 
Css positioning
Css positioningCss positioning
Css positioning
 
22 Methodology of problem solving
22 Methodology of problem solving22 Methodology of problem solving
22 Methodology of problem solving
 
04 Console input output-
04 Console input output-04 Console input output-
04 Console input output-
 
Creating a CSS layout from scratch
Creating a CSS layout from scratchCreating a CSS layout from scratch
Creating a CSS layout from scratch
 
Floating
FloatingFloating
Floating
 
Steps for CSS Layout
Steps for CSS LayoutSteps for CSS Layout
Steps for CSS Layout
 
12 Exceptions handling
12 Exceptions handling12 Exceptions handling
12 Exceptions handling
 
08 Numeral systems
08 Numeral systems08 Numeral systems
08 Numeral systems
 
03 Operators and expressions
03 Operators and expressions03 Operators and expressions
03 Operators and expressions
 
15 Text files
15 Text files15 Text files
15 Text files
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statements
 
19 Algorithms and complexity
19 Algorithms and complexity19 Algorithms and complexity
19 Algorithms and complexity
 
01 Introduction to programming
01 Introduction to programming01 Introduction to programming
01 Introduction to programming
 

Similar to 09 Methods

Methods intro-1.0
Methods intro-1.0Methods intro-1.0
Methods intro-1.0
BG Java EE Course
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
Svetlin Nakov
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
AnkitaVerma776806
 
Chapter 2.4
Chapter 2.4Chapter 2.4
Chapter 2.4sotlsoc
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
3. control statements
3. control statements3. control statements
3. control statements
amar kakde
 
Refactoring
RefactoringRefactoring
Refactoring
Mikalai Alimenkou
 
Psuedocode1, algorithm1, Flowchart1.pptx
Psuedocode1, algorithm1, Flowchart1.pptxPsuedocode1, algorithm1, Flowchart1.pptx
Psuedocode1, algorithm1, Flowchart1.pptx
MattFlordeliza1
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamed
Md Showrov Ahmed
 
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source SoftwareThe Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
Andrey Karpov
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
Haard Shah
 
Clean code
Clean codeClean code
Clean code
Henrique Smoco
 
Intake 38 data access 3
Intake 38 data access 3Intake 38 data access 3
Intake 38 data access 3
Mahmoud Ouf
 
Cis355 a ilab 2 control structures and user defined methods devry university
Cis355 a ilab 2 control structures and user defined methods devry universityCis355 a ilab 2 control structures and user defined methods devry university
Cis355 a ilab 2 control structures and user defined methods devry universitysjskjd709707
 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
Snehal Harawande
 

Similar to 09 Methods (20)

Methods intro-1.0
Methods intro-1.0Methods intro-1.0
Methods intro-1.0
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
Chapter 2.4
Chapter 2.4Chapter 2.4
Chapter 2.4
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
3. control statements
3. control statements3. control statements
3. control statements
 
Refactoring
RefactoringRefactoring
Refactoring
 
Psuedocode1, algorithm1, Flowchart1.pptx
Psuedocode1, algorithm1, Flowchart1.pptxPsuedocode1, algorithm1, Flowchart1.pptx
Psuedocode1, algorithm1, Flowchart1.pptx
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamed
 
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source SoftwareThe Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
 
Foundations of Programming Part I
Foundations of Programming Part IFoundations of Programming Part I
Foundations of Programming Part I
 
Clean code
Clean codeClean code
Clean code
 
Intake 38 data access 3
Intake 38 data access 3Intake 38 data access 3
Intake 38 data access 3
 
Unit1 C
Unit1 CUnit1 C
Unit1 C
 
Unit1 C
Unit1 CUnit1 C
Unit1 C
 
06 procedures
06 procedures06 procedures
06 procedures
 
Cis355 a ilab 2 control structures and user defined methods devry university
Cis355 a ilab 2 control structures and user defined methods devry universityCis355 a ilab 2 control structures and user defined methods devry university
Cis355 a ilab 2 control structures and user defined methods devry university
 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
 

More from maznabili

21 high-quality programming code construction part-i
21 high-quality programming code construction part-i21 high-quality programming code construction part-i
21 high-quality programming code construction part-i
maznabili
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphs
maznabili
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
maznabili
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classes
maznabili
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processing
maznabili
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
maznabili
 
10 Recursion
10 Recursion10 Recursion
10 Recursion
maznabili
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
maznabili
 
06 Loops
06 Loops06 Loops
06 Loops
maznabili
 
02 Primitive data types and variables
02 Primitive data types and variables02 Primitive data types and variables
02 Primitive data types and variables
maznabili
 

More from maznabili (10)

21 high-quality programming code construction part-i
21 high-quality programming code construction part-i21 high-quality programming code construction part-i
21 high-quality programming code construction part-i
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphs
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classes
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processing
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
10 Recursion
10 Recursion10 Recursion
10 Recursion
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
 
06 Loops
06 Loops06 Loops
06 Loops
 
02 Primitive data types and variables
02 Primitive data types and variables02 Primitive data types and variables
02 Primitive data types and variables
 

Recently uploaded

LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 

Recently uploaded (20)

LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 

09 Methods

  • 1. MethodsMethods Subroutines in Computer ProgrammingSubroutines in Computer Programming Svetlin NakovSvetlin Nakov Telerik CorporationTelerik Corporation www.telerik.comwww.telerik.com
  • 2. Table of ContentsTable of Contents 1.1. Using MethodsUsing Methods  What is a Method? Why to Use Methods?What is a Method? Why to Use Methods?  Declaring and Creating MethodsDeclaring and Creating Methods  Calling MethodsCalling Methods 1.1. Methods with ParametersMethods with Parameters  Passing ParametersPassing Parameters  Returning ValuesReturning Values 1.1. Best PracticesBest Practices 2
  • 3. What is a Method?What is a Method?  AA methodmethod is a kind of building block that solvesis a kind of building block that solves a small problema small problem A piece of code that has a name and can beA piece of code that has a name and can be called from the other codecalled from the other code Can take parameters and return a valueCan take parameters and return a value  Methods allow programmers to construct largeMethods allow programmers to construct large programs from simple piecesprograms from simple pieces  Methods are also known asMethods are also known as functionsfunctions,, proceduresprocedures, and, and subroutinessubroutines 3
  • 4. 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
  • 5. Declaring andDeclaring and Creating MethodsCreating Methods
  • 6. Declaring and Creating MethodsDeclaring and Creating Methods  Each method has aEach 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"); }} MethodMethod namename 6
  • 7. Declaring and Creating Methods (2)Declaring and Creating Methods (2)  Methods declaredMethods declared staticstatic can be called bycan be called by any other method (static or not)any other method (static or not) This will be discussed later in detailsThis will be discussed later in details  The keywordThe keyword voidvoid means that the methodmeans that the method does not return any resultdoes 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
  • 8. 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 Methods (3)Declaring and Creating Methods (3)  Each method has aEach method has a bodybody  It contains the programming codeIt contains the programming code  Surrounded bySurrounded by {{ andand }} MethodMethod bodybody 8
  • 9. 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 Methods (4)Declaring and Creating Methods (4)  Methods are always declared inside aMethods are always declared inside a classclass  Main()Main() is also a method like all othersis also a method like all others 9
  • 11. 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 method’sThis will execute the code in the method’s body and will result in printing the following:body and will result in printing the following: PrintLogo();PrintLogo(); Telerik Corp.Telerik Corp. www.telerik.comwww.telerik.com 11
  • 12. Calling Methods (2)Calling Methods (2)  A method can be called from:A method can be called from: TheThe Main()Main() methodmethod Any other methodAny other method Itself (process known asItself (process known as recursionrecursion)) static void Main()static void Main() {{ // ...// ... PrintLogo();PrintLogo(); // ...// ... }} 12
  • 13. Declaring andDeclaring and Calling MethodsCalling Methods Live DemoLive Demo
  • 14. Methods with ParametersMethods with Parameters Passing Parameters and Returning ValuesPassing Parameters and Returning Values
  • 15. Method ParametersMethod Parameters  To pass information to a method, you can useTo pass information to a method, you can use parametersparameters (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 valuesParameters are assigned to particular values when the method is calledwhen the method is called  Parameters can change the method behaviorParameters can change the method behavior depending on the passed valuesdepending on the passed values 15
  • 16. Defining and UsingDefining and Using Method ParametersMethod Parameters  Method’s behavior depends on its parametersMethod’s behavior depends on its parameters  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
  • 17. Defining and UsingDefining and Using Method Parameters (2)Method Parameters (2)  Methods can have as many parameters asMethods can have as many parameters as needed: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
  • 18. Calling MethodsCalling Methods with Parameterswith Parameters  To call a method and pass values to itsTo call a method and pass values to its parameters:parameters: Use the method’s name, followed by a list ofUse the method’s name, followed by a list of expressions for each parameterexpressions for each parameter  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
  • 19. Calling MethodsCalling Methods with Parameters (2)with Parameters (2)  Expressions must be of the same type asExpressions must be of the same type as method’s parameters (or compatible)method’s parameters (or compatible) If the method requires aIf the method requires a floatfloat expression, youexpression, you can passcan pass intint insteadinstead  Use the same order like in method declarationUse the same order like in method declaration  For methods with no parameters do not forgetFor methods with no parameters do not forget the parenthesesthe parentheses 19
  • 21. Methods Parameters – ExampleMethods Parameters – Example static void PrintSign(int number)static void PrintSign(int number) {{ if (number > 0)if (number > 0) Console.WriteLine("The number {0} is positive.", number);Console.WriteLine("The number {0} is positive.", number); else if (number < 0)else if (number < 0) Console.WriteLine("The number {0} is negative.", number);Console.WriteLine("The number {0} is negative.", number); elseelse Console.WriteLine("The number {0} is zero.", number);Console.WriteLine("The number {0} is zero.", 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
  • 22. Live DemoLive Demo Method ParametersMethod Parameters
  • 23. Months – ExampleMonths – Example  Display the period between two months in aDisplay the period between two months in a user-friendly wayuser-friendly way using 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
  • 24. 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 ", period);Console.Write("There are {0} " + months from ", period); SayMonth(startMonth);SayMonth(startMonth); Console.Write(" to ");Console.Write(" to "); SayMonth(endMonth);SayMonth(endMonth); }} }} 24
  • 26. Printing Triangle – ExamplePrinting Triangle – Example  Creating a program for printing triangles asCreating a program for printing triangles as shown below:shown below: 11 11 1 21 2 1 21 2 1 2 31 2 3 1 2 31 2 3 1 2 3 41 2 3 4 1 2 3 41 2 3 4 1 2 3 4 51 2 3 4 5 n=5n=5  1 2 3 4 51 2 3 4 5 n=6n=6  1 2 3 4 5 61 2 3 4 5 6 1 2 3 41 2 3 4 1 2 3 4 51 2 3 4 5 1 2 31 2 3 1 2 3 41 2 3 4 1 21 2 1 2 31 2 3 11 1 21 2 11 26
  • 27. Printing Triangle – ExamplePrinting Triangle – Example 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
  • 29. Optional ParametersOptional Parameters  C# 4.0 supports optional parameters with defaultC# 4.0 supports optional parameters with default values:values:  The above method can be called in several ways:The above method can be called in 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
  • 32. Returning Values From MethodsReturning Values From Methods  A method canA method can returnreturn a value to its callera value to its caller  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
  • 33. Defining MethodsDefining Methods That Return a ValueThat Return a Value  Instead ofInstead of voidvoid, specify the type of data to return, specify the type of data to return  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 anythingmethods do not return anything  The combination of method's name, parametersThe combination of method's name, parameters and return value is calledand return value is called method signaturemethod signature  UseUse returnreturn keyword to return a resultkeyword 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
  • 34. TheThe returnreturn StatementStatement  TheThe returnreturn statement:statement: Immediately terminates method’s executionImmediately terminates method’s execution Returns specified expression to the callerReturns specified expression to the caller Example:Example:  To terminateTo terminate voidvoid method, use just:method, use just:  Return can be used several times in a methodReturn can be used several times in a method bodybody return -1; return; 34
  • 37. TemperatureTemperature Conversion – ExampleConversion – Example  Convert temperature from Fahrenheit toConvert temperature from Fahrenheit to Celsius: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
  • 38. Live DemoLive Demo Temperature ConversionTemperature Conversion
  • 39. Positive Numbers – ExamplePositive Numbers – Example  Check if all numbers in a sequence are positive:Check if all numbers in a sequence 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
  • 40. Live DemoLive Demo Positive NumbersPositive Numbers
  • 41. Data Validation – ExampleData Validation – Example  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
  • 42. Data Validation – ExampleData Validation – Example 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
  • 44. Methods – Best PracticesMethods – Best Practices  Each method should perform a single,Each method should perform a single, well-defined taskwell-defined task  Method’s name should describe thatMethod’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 letterIn C# methods should start with capital letter  Avoid methods longer than one screenAvoid methods longer than one screen Split them to several shorter methodsSplit them to several shorter methods 44
  • 45. SummarySummary  Break large programs into simple methodsBreak large programs into simple methods that solve small sub-problemsthat solve small sub-problems  Methods consist of declaration and bodyMethods consist of declaration and body  Methods are invoked by their nameMethods are invoked by their name  Methods can accept parametersMethods can accept parameters  Parameters take actual values when calling aParameters take actual values when calling a methodmethod  Methods can return a value or nothingMethods can return a value or nothing 45
  • 47. ExercisesExercises 1.1. Write a method that asks the user for his name andWrite a method that asks the user for his name and prints “Hello, <name>” (for example, “Hello,prints “Hello, <name>” (for example, “Hello, Peter!”). Write a program to test this method.Peter!”). Write a program to test this method. 2.2. Write a methodWrite a method GetMax()GetMax() with two parameters thatwith two parameters that returns the bigger of two integers. Write a programreturns the bigger of two integers. Write a program that reads 3 integers from the console and prints thethat reads 3 integers from the console and prints the biggest of them using the methodbiggest of them using the method GetMax()GetMax().. 3.3. Write a method that returns the last digit of givenWrite a method that returns the last digit of given integer as an English word. Examples: 512integer as an English word. Examples: 512  "two","two", 10241024  "four", 12309"four", 12309  "nine"."nine". 47
  • 48. Exercises (2)Exercises (2) 4.4. Write a method that counts how many times givenWrite a method that counts how many times given number appears in given array. Write a test programnumber appears in given array. Write a test program to check if the method is working correctly.to check if the method is working correctly. 5.5. Write a method that checks if the element at givenWrite a method that checks if the element at given position in given array of integers is bigger than itsposition in given array of integers is bigger than its two neighbors (when such exist).two neighbors (when such exist). 6.6. Write a method that returns the index of the firstWrite a method that returns the index of the first element in array that is bigger than its neighbors, orelement in array that is bigger than its neighbors, or -1, if there’s no such element.-1, if there’s no such element.  Use the method from the previous exercise.Use the method from the previous exercise. 48
  • 49. Exercises (3)Exercises (3) 7.7. Write a method that reverses the digits of givenWrite a method that reverses the digits of given decimal number. Example: 256decimal number. Example: 256  652652 8.8. Write a method that adds two positive integerWrite a method that adds two positive integer numbers represented as arrays of digits (each arraynumbers represented as arrays of digits (each array elementelement arr[iarr[i]] contains a digit; the last digit iscontains a digit; the last digit is kept inkept in arr[0]arr[0]). Each of the numbers that will be). Each of the numbers that will be added could have up to 10 000 digits.added could have up to 10 000 digits. 9.9. Write a method that return the maximal element inWrite a method that return the maximal element in a portion of array of integers starting at given index.a portion of array of integers starting at given index. Using it write another method that sorts an array inUsing it write another method that sorts an array in ascending / descending order.ascending / descending order. 49
  • 50. Exercises (4)Exercises (4) 10.10. Write a program to calculateWrite a program to calculate n!n! for eachfor each nn in thein the rangerange [1..100][1..100]. Hint: Implement first a method. Hint: Implement first a method that multiplies a number represented as array ofthat multiplies a number represented as array of digits by given integer number.digits by given integer number. 11.11. Write a method that adds two polynomials.Write a method that adds two polynomials. Represent them as arrays of their coefficients as inRepresent them as arrays of their coefficients as in the example below:the example below: xx22 + 5 = 1+ 5 = 1xx22 + 0+ 0xx + 5+ 5  10.10. Extend the program to support also subtraction andExtend the program to support also subtraction and multiplication of polynomials.multiplication of polynomials. 55 00 11 50
  • 51. Exercises (5)Exercises (5) 13.13. Write a program that can solve these tasks:Write a program that can solve these tasks:  Reverses the digits of a numberReverses the digits of a number  Calculates the average of a sequence of integersCalculates the average of a sequence of integers  Solves a linear equationSolves a linear equation aa ** xx ++ bb = 0= 0 Create appropriate methods.Create appropriate methods. Provide a simple text-based menu for the user toProvide a simple text-based menu for the user to choose which task to solve.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 toshould not be equal to 00 51