This document discusses methods (also called subroutines or functions) in computer programming. It explains that methods allow programmers to break programs into smaller pieces to make them more organized and reusable. The document covers declaring and creating methods, passing parameters to methods, and methods returning values. Examples are provided to demonstrate methods with parameters and methods that return values.
In this chapter we will discuss exceptions in the object-oriented programming and in C# in particular. We will learn how to handle exceptions using the try-catch construct, how to pass them to the calling methods and how to throw standard or our own exceptions using the throw construct. We will give various examples for using exceptions. We will look at the types of exceptions and the exceptions hierarchy in the .NET Framework. At the end, we will look at the advantages of using exceptions, best practices and how to apply them in different situations.
In this chapter we will get more familiar with what methods are and why we need to use them. The reader will be shown how to declare methods, what parameters are and what a method’s signature is, how to call a method, how to pass arguments of methods and how methods return values. At the end of this chapter we will know how to create our own method and how to use (invoke) it whenever necessary. Eventually, we will suggest some good practices in working with methods. The content of this chapter accompanied by detailed examples and exercises that will help the reader practice the learned material.
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
In this chapter we will get acquainted with the operators in Java and the actions they can perform on the different data types. We will explain the priorities of the operators and we will analyze the different types of operators, according to the count of the arguments they can take and the actions they can perform. In the second part we will examine the conversion of data types.
In this chapter we will get familiar with primitive types and variables in Java – what they are and how to work with them. First we will consider the data types – integer types, real types with floating-point, Boolean, character, string and object type. We will continue with the variables, with their characteristics, how to declare them, how they are assigned a value and what is variable initialization.
19. Data Structures and Algorithm ComplexityIntro C# Book
In this chapter we will compare the data structures we have learned so far by the performance (execution speed) of the basic operations (addition, search, deletion, etc.). We will give specific tips in what situations what data structures to use. We will explain how to choose between data structures like hash-tables, arrays, dynamic arrays and sets implemented by hash-tables or balanced trees. Almost all of these structures are implemented as part of NET Framework, so to be able to write efficient and reliable code we have to learn to apply the most appropriate structures for each situation.
In this chapter we will discuss exceptions in the object-oriented programming and in C# in particular. We will learn how to handle exceptions using the try-catch construct, how to pass them to the calling methods and how to throw standard or our own exceptions using the throw construct. We will give various examples for using exceptions. We will look at the types of exceptions and the exceptions hierarchy in the .NET Framework. At the end, we will look at the advantages of using exceptions, best practices and how to apply them in different situations.
In this chapter we will get more familiar with what methods are and why we need to use them. The reader will be shown how to declare methods, what parameters are and what a method’s signature is, how to call a method, how to pass arguments of methods and how methods return values. At the end of this chapter we will know how to create our own method and how to use (invoke) it whenever necessary. Eventually, we will suggest some good practices in working with methods. The content of this chapter accompanied by detailed examples and exercises that will help the reader practice the learned material.
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
In this chapter we will get acquainted with the operators in Java and the actions they can perform on the different data types. We will explain the priorities of the operators and we will analyze the different types of operators, according to the count of the arguments they can take and the actions they can perform. In the second part we will examine the conversion of data types.
In this chapter we will get familiar with primitive types and variables in Java – what they are and how to work with them. First we will consider the data types – integer types, real types with floating-point, Boolean, character, string and object type. We will continue with the variables, with their characteristics, how to declare them, how they are assigned a value and what is variable initialization.
19. Data Structures and Algorithm ComplexityIntro C# Book
In this chapter we will compare the data structures we have learned so far by the performance (execution speed) of the basic operations (addition, search, deletion, etc.). We will give specific tips in what situations what data structures to use. We will explain how to choose between data structures like hash-tables, arrays, dynamic arrays and sets implemented by hash-tables or balanced trees. Almost all of these structures are implemented as part of NET Framework, so to be able to write efficient and reliable code we have to learn to apply the most appropriate structures for each situation.
In this chapter we are going to get familiar with recursion and its applications. Recursion represents a powerful programming technique in which a method makes a call to itself from within its own method body. By means of recursion we can solve complicated combinatorial problems, in which we can easily exhaust different combinatorial configurations, e.g. generating permutations and variations and simulating nested loops. We are going to demonstrate many examples of correct and incorrect usage of recursion and convince you how useful it can be.
C programming, RTS Tech. Indore
This is a presentation to take your skills to next level. Hope you will like our work to make programming easier for you.
Feel free to contact for the online/offline batches.
In this chapter we will get familiar with the console as a tool for data input and output. We will explain what it is, when and how to use it, and how most programming languages access the console. We will get familiar with some of the features in C# for user interaction: reading text and numbers from the console and printing text and numbers. We will also examine the main streams for input-output operations Console.In, Console.Out and Console.Error, the Console and the usage of format strings for printing data in various formats.
Скомпилировалось — значит работает. К сожалению это выражение не про typescript. Кажется, что количество рантайм ошибок спровоцированных несоответствием типов должно стать меньше, однако компилятор ts не помогает разработчику писать качественный код, а наоборот поощряет использование грязных хаков. Филипп Сапронов рассказывает, как прекратить войну с компилятором и писать более надёжный код, используя всю мощь системы типов. Доклад будет интересен тем, кому ts кажется простым или наоборот сложным, а также тем, кто хочет научится понимать код тайпингов таких библиотек как lodash.
Python Exception Handling
This is a presentation to take your skills to next level. Hope you will like our work to make programming easier for you.
Feel free to contact for the online/offline batches.
In this chapter we will cover the conditional statements in C#, which we can use to execute different actions depending on a given condition. We will explain the syntax of the conditional operators if and if-else with suitable examples and explain the practical application of the operator for selection switch-case.
Python: Object oriented programming, RTS Tech. Indore
This is a presentation to take your skills to next level. Hope you will like our work to make programming easier for you.
Feel free to contact for the online/offline batches.
Esoft Metro Campus - Certificate in c / c++ programmingRasan Samarasinghe
Esoft Metro Campus - Certificate in java basics
(Template - Virtusa Corporate)
Contents:
Structure of a program
Variables & Data types
Constants
Operators
Basic Input/output
Control Structures
Functions
Arrays
Character Sequences
Pointers and Dynamic Memory
Unions
Other Data Types
Input/output with files
Searching
Sorting
Introduction to data structures
In this chapter we are going to get familiar with recursion and its applications. Recursion represents a powerful programming technique in which a method makes a call to itself from within its own method body. By means of recursion we can solve complicated combinatorial problems, in which we can easily exhaust different combinatorial configurations, e.g. generating permutations and variations and simulating nested loops. We are going to demonstrate many examples of correct and incorrect usage of recursion and convince you how useful it can be.
C programming, RTS Tech. Indore
This is a presentation to take your skills to next level. Hope you will like our work to make programming easier for you.
Feel free to contact for the online/offline batches.
In this chapter we will get familiar with the console as a tool for data input and output. We will explain what it is, when and how to use it, and how most programming languages access the console. We will get familiar with some of the features in C# for user interaction: reading text and numbers from the console and printing text and numbers. We will also examine the main streams for input-output operations Console.In, Console.Out and Console.Error, the Console and the usage of format strings for printing data in various formats.
Скомпилировалось — значит работает. К сожалению это выражение не про typescript. Кажется, что количество рантайм ошибок спровоцированных несоответствием типов должно стать меньше, однако компилятор ts не помогает разработчику писать качественный код, а наоборот поощряет использование грязных хаков. Филипп Сапронов рассказывает, как прекратить войну с компилятором и писать более надёжный код, используя всю мощь системы типов. Доклад будет интересен тем, кому ts кажется простым или наоборот сложным, а также тем, кто хочет научится понимать код тайпингов таких библиотек как lodash.
Python Exception Handling
This is a presentation to take your skills to next level. Hope you will like our work to make programming easier for you.
Feel free to contact for the online/offline batches.
In this chapter we will cover the conditional statements in C#, which we can use to execute different actions depending on a given condition. We will explain the syntax of the conditional operators if and if-else with suitable examples and explain the practical application of the operator for selection switch-case.
Python: Object oriented programming, RTS Tech. Indore
This is a presentation to take your skills to next level. Hope you will like our work to make programming easier for you.
Feel free to contact for the online/offline batches.
Esoft Metro Campus - Certificate in c / c++ programmingRasan Samarasinghe
Esoft Metro Campus - Certificate in java basics
(Template - Virtusa Corporate)
Contents:
Structure of a program
Variables & Data types
Constants
Operators
Basic Input/output
Control Structures
Functions
Arrays
Character Sequences
Pointers and Dynamic Memory
Unions
Other Data Types
Input/output with files
Searching
Sorting
Introduction to data structures
If you are the copyright holder of one of the photos used in this presentation and you would not like it to be used in an academic context, please contact me and I will remove the image from the presentation. I have made sure that only images are use that are available under the Creative Commons licence.
Learn about how to define and invoke methods in Java, how to use parameters and return results. Watch the video lesson here:
https://softuni.org/code-lessons/java-foundations-certification-methods
you will learn how to create your own methods with or without return values, invoke a method with or without parameters, and apply method abstraction in the program design.
This page contains examples and source code on decision making in C programming (to choose a particular statement among many statements) and loops ( to perform repeated task ). To understand all the examples on this page, you should have knowledge of following topics:
if...else Statement
for Loop
while Loop
break and Continue Statement
switch...case
A summary of clean code concepts and tips along with some examples and good practices.
These are the slides translated in English from my talk on Clean Code to my coworkers back then
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
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
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
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
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
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
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
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
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