Presentation is loading. Please wait.

Presentation is loading. Please wait.

Subroutines in Computer Programming

Similar presentations


Presentation on theme: "Subroutines in Computer Programming"— Presentation transcript:

1 Subroutines in Computer Programming
Functions Subroutines in Computer Programming Telerik Software Academy Learning & Development Team

2 Table of Contents Using Functions Functions with Parameters
* Table of Contents Using Functions What is a Function? Why to Use Functions? Declaring and Creating Functions Calling Functions Functions with Parameters Passing Parameters Returning Values Best Practices (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

3 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

4 Why to Use Functions? More manageable programming
* 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 (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

5 * Defining Functions (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

6 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

7 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

8 Defining and Creating Functions (3)
int max(int num1, int num2) { int result = min2; if (num1 > num2) result = num1; return result; } Function body Each Function has a body It contains the programming code Surrounded by { and }

9 * Declaring Functions (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

10 Declaring Functions Declaring function has these parts Example:
You can also use: Declaring is used when you define a function in one file and call it in another return_type function_name( parameter list ); int max(int num1, int num2); int max(int, int);

11 Calling Functions

12 Calling Functions To call a Function, simply use:
The Function’s name Parentheses (don’t forget them!) A semicolon (;) This will execute the code in the Function’s body int a = 5; Int b = 6; int ret = max(a, b);

13 Calling Functions (2) A Function can be called from:
The Main() Function Any other Function Itself (process known as recursion) int main () { // ... int ret = max(a, b); }

14 Declaring and Calling Functions
* Declaring and Calling Functions Live Demo (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

15 Functions with Parameters
* Functions with Parameters Passing Parameters and Returning Values (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

16 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

17 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

18 Defining and Using Function Parameters (2)
Functions can have as many parameters as needed: The following syntax is not valid: int max(int num1, int num2) { int result = min2; if (num1 > num2) result = num1; return result; } int max(int num1, num2)

19 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);

20 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

21 Using Functions With Parameters
* Using Functions With Parameters Examples (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

22 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)

23 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);

24 * Months Live Demo (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

25 Printing Triangle – Example
Creating a program for printing triangles as shown below: 1 1 1 2 n=5  n=6 

26 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);

27 Printing Triangle Live Demo

28 Optional Parameters C++ supports default values assigned at their declaration: The above Function can be called in several ways: int sum(int a = 10, int b = 20) { int result; result = a + b; return (result); } sum(5, 10); sum(15); sum();

29 Optional Parameters Live Demo

30 Returning Values From Functions
* Returning Values From Functions (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

31 Returning Values From Functions
A Function can return a value to its caller Returned value: Can be assigned to a variable: Can be used in expressions: Can be passed to another Function: int a = max(b, c); int price = getPrice() * q * 1.20; int age = max(getValue());

32 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

33 The return Statement The return statement:
Immediately terminates Function’s execution Returns specified expression to the caller Example: To terminate void Function, use just: Return can be used several times in a Function body return -1; return;

34 Returning Values From Functions
* Returning Values From Functions Examples (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

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

36 Positive Numbers Live Demo *
(c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

37 Overloading Functions
Multiple Functions with the Same Name

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

39 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

40 * 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 (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

41 Functions

42 * Exercises 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. 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(). Write a Function that returns the last digit of given integer as an English word. Examples: 512  "two",  "four",  "nine". (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

43 Exercises (2) 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. 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). 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.

44 * Exercises (3) Write a Function that reverses the digits of given decimal number. Example: 256  652 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 digits. 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. (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

45 Exercises (4) 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. Write a Function that adds two polynomials. Represent them as arrays of their coefficients as in the example below: x2 + 5 = 1x2 + 0x + 5  Extend the program to support also subtraction and multiplication of polynomials. 5 1

46 Exercises (5) Write a program that can solve these tasks:
* Exercises (5) 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 (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

47 * Exercises (6) Write Functions to calculate minimum, maximum, average, sum and product of given set of integer numbers. Use variable number of arguments. * 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#). (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

48 Free Trainings @ Telerik Academy
“C# Telerik Academy csharpfundamentals.telerik.com Telerik Software Academy academy.telerik.com Telerik Facebook facebook.com/TelerikAcademy Telerik Software Academy Forums forums.academy.telerik.com


Download ppt "Subroutines in Computer Programming"

Similar presentations


Ads by Google