Subroutines in Computer Programming

Slides:



Advertisements
Similar presentations
Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
Advertisements

Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Computer Science 1620 Loops.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
1.9 Methods academy.zariba.com 1. Lecture Content 1.What is a method? Why use methods? 2.Void Methods and methods with parameters 3.Methods which return.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
Section 4 - Functions. All of the programs that we have studied so far have consisted of a single function, main(). However, having more than one function.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Subroutines in Computer Programming Telerik School Academy C# Fundamentals – Part 1.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
GE 211 Dr. Ahmed Telba. // compound assignment operators #include using namespace std; int main () { a =5 int a, b=3; a = b; a+=2; // equivalent to a=a+2.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
Reusable parts of Code Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Programming Fundamentals Enumerations and Functions.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Chapter 8 Functions.
Chapter 1.2 Introduction to C++ Programming
Chapter 9: Value-Returning Functions
EGR 2261 Unit 11 Pointers and Dynamic Variables
Review 1.
Chapter Topics The Basics of a C++ Program Data Types
User-Written Functions
Java Language Basics.
Chapter 6: User-Defined Functions I
Chapter 1.2 Introduction to C++ Programming
Repeating Code Multiple Times
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 1.2 Introduction to C++ Programming
Multidimensional Arrays
Basic Elements of C++.
Introduction to C++ Introduced by Bjarne Stroustrup of AT&T’s Bell Laboratories in mid-1980’s Based on C C++ extended C to support object-oriented programming.
Functions and an Introduction to Recursion
The Selection Structure
Binary, Decimal and Hexadecimal Numbers
Introduction to C++ October 2, 2017.
JavaScript: Functions.
User-Defined Functions
Basic Elements of C++ Chapter 2.
User-defined Functions
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Starting JavaProgramming
Chapter 5 Function Basics
Additional Control Structures
6 Chapter Functions.
User-defined Functions
Introduction to C++ Introduced by Bjarne Stroustrup of AT&T’s Bell Laboratories in mid-1980’s Based on C C++ extended C to support object-oriented programming.
Computing Fundamentals
Chapter 6: User-Defined Functions I
Functions and an Introduction to Recursion
Methods.
C++ Programming Lecture 3 C++ Basics – Part I
Chapter 5: Control Structures II (Repetition)
CHAPTER 4: Lists, Tuples and Dictionaries
Predefined Functions Revisited
Functions Imran Rashid CTO at ManiWeber Technologies.
CS 144 Advanced C++ Programming January 31 Class Meeting
各題答對人數.
Presentation transcript:

Subroutines in Computer Programming Functions Subroutines in Computer Programming Telerik Software Academy Learning & Development Team http://academy.telerik.com

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 - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

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

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 - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

* Defining Functions (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

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

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

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 }

* Declaring Functions (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

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

Calling Functions

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

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

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

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

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

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

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)

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

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

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

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)

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

* Months Live Demo (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

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

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

Printing Triangle Live Demo

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

Optional Parameters Live Demo

Returning Values From Functions * Returning Values From Functions (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

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

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

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;

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

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;

Positive Numbers Live Demo * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

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;

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

* 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 - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

Functions http://csharpfundamentals.telerik.com

* 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", 1024  "four", 12309  "nine". (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

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.

* 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 10 000 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 - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

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

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 - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

* 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 - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

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