Download Calling Functions

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts

Mathematics of radio engineering wikipedia, lookup

Big O notation wikipedia, lookup

Functional decomposition wikipedia, lookup

Non-standard calculus wikipedia, lookup

Elementary mathematics wikipedia, lookup

Continuous function wikipedia, lookup

Principia Mathematica wikipedia, lookup

Dirac delta function wikipedia, lookup

Function (mathematics) wikipedia, lookup

History of the function concept wikipedia, lookup

Function of several real variables wikipedia, lookup

Transcript
Functions
Subroutines in Computer Programming
Telerik Software Academy
Learning & Development Team
http://academy.telerik.com
Table of Contents
1.
Using Functions
 What is a Function? Why to Use Functions?
 Declaring and Creating Functions
 Calling Functions
2.
Functions with Parameters
 Passing Parameters
 Returning Values
3.
Best Practices
2
What is a Function?
 A Function is a kind of building
block that
solves a small problem
 A piece of code that has a name and can be
called from the other code
 Can take parameters and return a value
 Functions allow
programmers to construct
large programs from simple pieces
 Functions are also
known as methods,
procedures, and subroutines
3
Why to Use Functions?
 More manageable programming
 Split large problems into small pieces
 Better organization of the program
 Improve code readability
 Improve code understandability
 Avoiding

repeating code
Improve code maintainability
 Code reusability
 Using existing Functions several times
4
Defining Functions
Defining and Creating Functions
return_type function_name( parameter list )
{
body of the function
}
 Each Function has a
name
 It is used to call the Function
 Describes its purpose
6
Defining and Creating Functions (2)
int max(int num1, int num2)
{
int result = min2;
if (num1 > num2) result = num1;
return result;
}
 Put return_type
void when the Function
does not return any result
7
Defining and Creating Functions (3)
int max(int num1, int num2)
{
int result = min2;
if (num1 > num2) result = num1;
return result;
}
Functio
n body
 Each Function has a body
 It contains
the programming code
 Surrounded by {
and }
8
Declaring
Functions
Declaring Functions
 Declaring function has these parts
return_type function_name( parameter list );
 Example:
int max(int num1, int num2);
 You can also
use:
int max(int, int);
 Declaring is used when you
define a function
in one file and call it in another
10
Calling Functions
Calling Functions
 To call a Function, simply
use:
1. The Function’s name
2. Parentheses (don’t forget them!)
3. A semicolon (;)
int a = 5;
Int b = 6;
int ret = max(a, b);
 This will
execute the code in the Function’s
body
12
Calling Functions (2)
 A Function can be called from:
 The Main() Function
int main ()
{
// ...
int ret = max(a, b);
// ...
}
 Any other Function
 Itself (process known as recursion)
13
Declaring and
Calling Functions
Live Demo
Functions with
Parameters
Passing Parameters and Returning Values
Function Parameters
 To pass
information to a Function, you can use
parameters (also known as arguments)
 You can pass zero or several input values
 You can pass values of different types
 Each parameter has name and type
 Parameters are assigned to particular values
when the Function is called
 Parameters
can change the Function behavior
depending on the passed values
16
Defining and Using
Function Parameters
 Function’s behavior depends on
its parameters
 Parameters can be of any type
 Call by value - copies value
 Call by pointer - copies memory address
 Call by reference - copies reference
 Call by pointer and by reference change the
passed argument into the function scope
17
Defining and Using
Function Parameters (2)
 Functions can have as many parameters as
needed:
int max(int num1, int num2)
{
int result = min2;
if (num1 > num2) result = num1;
return result;
}
 The following
syntax is not valid:
int max(int num1, num2)
18
Calling Functions
with Parameters
 To call a Function and pass
values to its
parameters:
 Use the Function’s name, followed by a list of
expressions for each parameter
 Examples:
PrintSign(-5);
PrintSign(balance);
PrintSign(2+3);
PrintMax(100, 200);
PrintMax(oldQuantity * 1.5, quantity * 2);
19
Calling Functions
with Parameters (2)
 Expressions
must be of the same type as
Function’s parameters (or compatible)
 If the Function requires a long expression, you
can pass int instead
 Use the same order like in Function declaration
 For Functions with no parameters do not
forget the parentheses
20
Using Functions
With Parameters
Examples
Months – Example
 Display
the period between two months in a
user-friendly way
#include <iostream>
using namespace std;
void SayMonth(int month)
{
string monthNames[] =
{
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
};
cout << monthNames[month-1];
}
(the example continues)
22
Months – Example (2)
void SayPeriod(int start, int end)
{
int period = end - start;
if (period < 0)
{
period += 12;
}
cout << "There are " << period << " months between " <<
SayMonth(start) << " and " << SayMonth(end);
}
23
Months
Live Demo
Printing Triangle – Example
 Creating
a program for printing triangles as
shown below:
n=5
1
1
1
1
 1
1
1
1
1
2
2
2
2
2
2
2
3
3 4
3 4 5
3 4
3
n=6

1
1
1
1
1
1
1
1
1
1
1
2
2
2
2
2
2
2
2
2
3
3
3
3
3
3
3
4
4 5
4 5 6
4 5
4
25
Printing Triangle – Example
void printLine(int start, int end)
{
for(int i = start; i <= end; i++)
{
cout << i << " ";
}
cout << endl;
}
int main()
{
int n;
cin >> n;
for(int i = 1; i <= n; i++) printLine(1, i);
for(int i = n - 1; i >= 1; i--) printLine(1, i);
}
26
Optional Parameters

C++ supports default values assigned at their
declaration:
int sum(int a = 10, int b = 20)
{
int result;
result = a + b;
return (result);
}

The above Function can be called in several ways:
sum(5, 10);
sum(15);
sum();
28
Optional Parameters
Live Demo
Returning Values
From Functions
Returning Values From Functions
 A Function can return a value to its caller
 Returned value:
 Can be assigned to a variable:
int a = max(b, c);
 Can be used in expressions:
int price = getPrice() * q * 1.20;
 Can be passed to another Function:
int age = max(getValue());
31
Defining Functions
That Return a Value

Instead of void, specify the type of data to return

Functions can return any type of data (int,
string, array, etc.)

void Functions do not return anything

The combination of Function's name and
parameters is called Function signature

Use return keyword to return a result
32
The return Statement
 The return statement:
 Immediately terminates Function’s execution
 Returns specified expression to the caller
 Example:
return -1;
 To terminate void Function, use just:
return;
 Return can be used several
times in a Function
body
33
Returning Values
From Functions
Examples
Positive Numbers – Example
 Check if all
numbers in a sequence are positive:
bool arePositive(int numbers[])
{
for(int i = 0; i < sizeof(numbers); i++)
{
if(numbers[i] < 0)
{
return false;
}
}
return true;
}
35
Positive Numbers
Live Demo
Overloading Functions
Multiple Functions with the Same Name
Overloading Functions
 What means "to
overload a Function name"?
 Use the same Function name for multiple
Functions with different signature (parameters)
int print(int a)
{
return a;
}
int print(int a, int b)
{
return a + b;
}
int print(int a, int b, int c)
{
return a + b + c;
}
38
Functions – Best Practices
 Each Function should perform a single,
well-defined task
 Function’s name should describe that
task in a clear and non-ambiguous way
 Good examples: calculatePrice, readName
 Bad examples: f, g1, Process
 In C# Functions should start with capital letter
 Avoid Functions longer than one screen
 Split them to several shorter Functions
39
Summary

Break large programs into simple Functions
that solve small sub-problems

Functions consist of declaration and body

Functions are invoked by their name

Functions can accept parameters
 Parameters take actual values when calling a
Function

Functions can return a value or nothing
40
Functions
курсове и уроци по програмиране, уеб дизайн – безплатно
курсове и уроци по програмиране – Телерик академия
уроци по програмиране и уеб дизайн за ученици
програмиране за деца – безплатни курсове и уроци
безплатен SEO курс - оптимизация за търсачки
курсове и уроци по програмиране, книги – безплатно от Наков
уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop
free C# book, безплатна книга C#, книга Java, книга C#
безплатен курс "Качествен програмен код"
безплатен курс "Разработка на софтуер в cloud среда"
BG Coder - онлайн състезателна система - online judge
форум програмиране, форум уеб дизайн
ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET
ASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC
алго академия – състезателно програмиране, състезания
курс мобилни приложения с iPhone, Android, WP7, PhoneGap
Дончо Минков - сайт за програмиране
Николай Костов - блог за програмиране
C# курс, програмиране, безплатно
http://csharpfundamentals.telerik.com
Exercises
1.
Write a Function that asks the user for his name and
prints “Hello, <name>” (for example, “Hello,
Peter!”). Write a program to test this Function.
2.
Write a Function getMax() with two parameters
that returns the bigger of two integers. Write a
program that reads 3 integers from the console and
prints the biggest of them using the Function
getMax().
3.
Write a Function that returns the last digit of given
integer as an English word. Examples: 512  "two",
1024  "four", 12309  "nine".
42
Exercises (2)
4.
Write a Function that counts how many times given
number appears in given array. Write a test program
to check if the Function is working correctly.
5.
Write a Function that checks if the element at given
position in given array of integers is bigger than its
two neighbors (when such exist).
6.
Write a Function that returns the index of the first
element in array that is bigger than its neighbors, or
-1, if there’s no such element.
 Use the Function from the previous exercise.
43
Exercises (3)
7.
Write a Function that reverses the digits of given
decimal number. Example: 256  652
8.
Write a Function that adds two positive integer
numbers represented as arrays of digits (each array
element arr[i] contains a digit; the last digit is
kept in arr[0]). Each of the numbers that will be
added could have up to 10 000 digits.
9.
Write a Function that return the maximal element in
a portion of array of integers starting at given index.
Using it write another Function that sorts an array in
ascending / descending order.
44
Exercises (4)
10.
Write a program to calculate n! for each n in the
range [1..100]. Hint: Implement first a Function
that multiplies a number represented as array of
digits by given integer number.
11.
Write a Function that adds two polynomials.
Represent them as arrays of their coefficients as in
the example below:
x2 + 5 = 1x2 + 0x + 5  5 0 1
12.
Extend the program to support also subtraction and
multiplication of polynomials.
45
Exercises (5)
13.
Write a program that can solve these tasks:
 Reverses the digits of a number
 Calculates the average of a sequence of integers
 Solves a linear equation a * x + b = 0
Create appropriate Functions.
Provide a simple text-based menu for the user to
choose which task to solve.
Validate the input data:
 The decimal number should be non-negative
 The sequence should not be empty
 a should not be equal to 0
46
Exercises (6)
14.
Write Functions to calculate minimum, maximum,
average, sum and product of given set of integer
numbers. Use variable number of arguments.
15.
* Modify your last program and try to make it work
for any number type, not just integer (e.g. decimal,
float, byte, etc.). Use generic Function (read in
Internet about generic Functions in C#).
47
Free Trainings @ Telerik Academy
 “C# Programming @ Telerik Academy


Telerik Software Academy


academy.telerik.com
Telerik Academy @ Facebook


csharpfundamentals.telerik.com
facebook.com/TelerikAcademy
Telerik Software Academy Forums

forums.academy.telerik.com