1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva.

Slides:



Advertisements
Similar presentations
1 Programming in C++ Lecture Notes 9 Functions (Returning Values) Andreas Savva.
Advertisements

True or false A variable of type char can hold the value 301. ( F )
Computer Science 1620 Loops.
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
C++ Pointer and Functions
Overview creating your own functions calling your own functions.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Programmer-defined functions Development of simple functions using value parameters.
Overview scope - determines when an identifier can be referenced in a program storage class - determines the period of time during which that identifier.
Programming in C++ Lecture Notes 2 – Choice Statements Andreas Savva.
C++ Programming Language Day 1. What this course covers Day 1 – Structure of C++ program – Basic data types – Standard input, output streams – Selection.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Lecture 9m: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 15 - C++ As A "Better C" Outline 15.1Introduction 15.2C A Simple Program: Adding Two Integers.
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.
1 10/18/04CS150 Introduction to Computer Science 1 Functions Divide and Conquer.
Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
1 COMS 261 Computer Science I Title: Functions Date: October 12, 2005 Lecture Number: 17.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-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.
C++ / G4MICE Course Session 1 - Introduction Edit text files in a UNIX environment. Use the g++ compiler to compile a single C++ file. Understand the C++
Manish K Parmar PGT (CS) K V VVNagar Thursday, December 24, 2015 Lesson on USER DEFINED FUNCTION IN C++ Presented by Manish K Parmar PGT Computer Science.
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Function Definition: Return_DT F_name (
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Lecture 5 Computer programming -1-. Input \ Output statement 1- Input (cin) : Use to input data from keyboard. Example : cin >> age; 2- Output (cout):
Programming Principles II Lecture Notes 3.1 Void Functions Andreas Savva.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
User-Defined Functions (cont’d) - Reference Parameters.
CSIS 123A Lecture 7 Static variables, destructors, & namespaces.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
A Sample Program #include using namespace std; int main(void) { cout
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Week 4 – Functions Coding Functions. Purpose of Coding Functions A function is written to perform a well-defined task; rather than having all logic in.
Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)
Chapter 1.2 Introduction to C++ Programming
IS Program Design and Software Tools Introduction to C++ Programming
Introduction to C++ Systems Programming.
Command Line Arguments
Functions and an Introduction to Recursion
School of EECS, Peking University
Chapter 5 Functions.
Arrays Part-1 Armen Keshishian.
Subroutines in Computer Programming
Chapter 9 Scope, Lifetime, and More on Functions
Chapter 5 Function Basics
Functions.
Functions and an Introduction to Recursion
Functions Divide and Conquer
Engineering Problem Solving with C++ An Object Based Approach
Functions Imran Rashid CTO at ManiWeber Technologies.
CS1201: Programming Language 2
Presentation transcript:

1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva

2 Functions in Mathematics f(x) = x 2 Parameters f(2) = f(-2) = f(4) = f(x,y) = x 2 +y f(2,3) = f(-2,-3) = 7 1 f = 3

3 Functions Function None or many inputparameters Exactly one return value

4 Functions that we know abs(-6)= 6 sqrt(16)= 4 sin( /2)= 1 int(45.876)= 45 absx|x| F(x) = |x|

5 Function Structure ( ) {..... return ; } bool IsBigger (int a, int b) { return a > b; }

6 Example int MySqr (int x) { return x * x; }Name Formal parameter Data type of return value Return value Functions are executed when we call them: cout << MySqr(6); y = 1 + MySqr(3-1); n = 3 * MySqr(abs(sqrt(9)-5));

7 Function - Example #include #include using namespace std; int cube(int); int main() { int n, x; int n, x; cout << ”Give a number: ”; cout << ”Give a number: ”; cin >> n; cin >> n; x = cube(n); x = cube(n); cout << ”The cube of ” << n << ” is ” << x; cout << ”The cube of ” << n << ” is ” << x; return 0; return 0;} int cube(int x) { return x * x * x; return x * x * x;}

8 #include using namespace std; char First (int a, int b; float c) {... return ; } void main() { int a = 1, b = 3, c = 7;... char ch = First (5, c, a); } Actual parameters Formal parameters Parameters (Arguments) Formal Formal Actual Actual

9 Function Example #include using namespace std; int max(int, int); // Function prototype int num; // Global variable void main() { cout << max(4,7); num = max(2*4-1, Sqrt(81)); cout << num; cout << max(max(4,5),8); cout << max(max(4,2),max(3,max(6,1))); } int max (int a, int b) { if (a > b) return a; else return b; } Result Result

10 Return return exits the function immediately and returns a value. return exits the function immediately and returns a value. int addone (int a) { return 1; cout << a + 1; a++; return a; cout << a; } Statements below this line will never be executed. Always return 1 int max(int a, int b) { if (a > b) return a; else return b; } int max(int a, int b) { if (a > b) return a; return b; } same

11 Be Careful int max(int a, int b) { int large; if (a > b) large = a; else large = b; return large; } int max(int a, int b) { int large; if (a > b) large = a; large = b; return large; } NOTthesame

12 Procedure Vs Function #include using namespace std; int num; Display void Display( ) { cout << ”I like college”; } MySqr int MySqr (int x) { return x * x; } void main( ) Display( ) Display( ); MySqr cout << MySqr(3); MySqr num = * MySqr(4); } Does not return a value Returns

13 Returning a Class class Fraction { public: int numerator; int denominator; }; Fraction init() { Fraction f; f.numerator = 5; f.denominator = 12; return f; } int main() { Fraction y; y = init(); cout << y.numerator << ’/’ << y.denominator; return 0; } 5/12

14 Receiving and Returning Classes class Fraction { public: int numerator; int denominator; }; Fraction multiply(Fraction a, Fraction b) { Fraction f; f.numerator = a.numerator * b.numerator; f.denominator = a.denominator * b.denominator; return f; } int main() { Fraction x = {2,3}, y = {5,7}, z; z = multiply(x, y); cout << z.numerator << ’/’ << z.denominator; return 0; } 10/21

15 Constant Reference Parameters Value formal parameters copy in a new memory location the value of the actual parameter. Value formal parameters copy in a new memory location the value of the actual parameter. When we have large structures it is better to use a reference formal parameter since copying could be time-consuming and we also waist additional memory. When we have large structures it is better to use a reference formal parameter since copying could be time-consuming and we also waist additional memory. We can declare a reference formal parameter as a constant which will not allow as to change its value (for safety). We can declare a reference formal parameter as a constant which will not allow as to change its value (for safety). void invalid(const int &x) { x = 5; // Syntax ERROR }

16 Constant Reference Parameters class Fraction { public: int numerator; int denominator; }; Fraction multiply(const Fraction &a, const Fraction &b) { Fraction f; f.numerator = a.numerator * b.numerator; f.denominator = a.denominator * b.denominator; return f; } int main() { Fraction x = {2,3}, y = {5,7}, z; z = multiply(x, y); cout << z.numerator << ’/’ << z.denominator; return 0; } 10/21

17 Returning Pointers int *result(int a, int b) { int *r = new int(a + b); return r; } int main() { int *z = result(5, 2); cout << *z; return 0; } 7

18 Formal Parameters void test(int a, int &b, int *c) { a = 12; b = 23; *c = 34; } int main() { int x = 2, y = 5, z = 7; test(x, y, &z); cout << x << endl << y << endl << z; return 0; } 22334

19 Pointer Referencing void test(int *&a) { a = new int(23); } int main() { int *p = new int(12); int *r = p; test(p); cout << *p << endl << *r; return 0; } 2312

20 main() is also a Function #include // standard system definitions library #include using namespace std; int main() { int x,y; cout << ”Please enter two numbers: ”; cin >> x >> y; int sum = x + y; cout << ”Their sum is ” << sum << endl; return EXIT_SUCCESS; }

21 main() can also take Parameters #include using namespace std; int main(int argc, char **argv) { if (argc > 1) if (strcmp(argv[1],”nicosia”)) cout << ”Not a valid password”; else cout << ”Logged in as administrator”; else cout << ”Regular user”; return 0; }

22 The Function main() #include using namespace std; int main(int argc, char **argv) { if (argc == 1) { cout << ”Enter n numbers to add\n”; exit(1); } int sum = 0; for (int i=1; i<argc; i++) sum += atoi(argv[i]); cout << ”Sum = ” << sum << endl; return 0; }

23 Exercise 1 Write a program that will ask the price of a product and display the discount. The discount should be returned by a function, called “Discount”, that will take the price as a formal parameter and return the discount which is 15%. Write a program that will ask the price of a product and display the discount. The discount should be returned by a function, called “Discount”, that will take the price as a formal parameter and return the discount which is 15%.

24 Exercise 2 Write a program to ask the base and height of a right-angle triangle and display its area. The area should be calculated and returned by a function, called “Area”, that will take the base and height as formal parameters. Write a program to ask the base and height of a right-angle triangle and display its area. The area should be calculated and returned by a function, called “Area”, that will take the base and height as formal parameters. Area = (Base x Height) / 2

25 Exercise 3 Write a function “Subtract” that will take two real parameters and return their difference. Also write the program that will read the numbers, call the function and display the result. Write a function “Subtract” that will take two real parameters and return their difference. Also write the program that will read the numbers, call the function and display the result.

26 Exercise 4 Write a function “Calculator” that will take two numbers a and b and a character, and if the character is: Write a function “Calculator” that will take two numbers a and b and a character, and if the character is: ’+’ to return a + b ’–’ to return a – b ’*’ to return a * b ’/’ to return a / b

27 Exercise 5 Write a function “Sum” that will take two integer numbers n and m and return the sum of all the numbers from n to m. Write a function “Sum” that will take two integer numbers n and m and return the sum of all the numbers from n to m.i.e. Sum(1,4) = = 10 Sum(1,4) = = 10 Sum(4,9) = = 39 Sum(4,9) = = 39 Sum(7,7) = 7 Sum(7,7) = 7 Sum(7,2) = 0 Sum(7,2) = 0

28 Exercise 6 Write a function “Month” that will take the month-number and return the month name. Write a function “Month” that will take the month-number and return the month name. i.e. Month(1) = “January” Month(1) = “January” Month(4) = “April” Month(4) = “April” Month(11) = “November” Month(11) = “November”

29 Exercise 7 Write a function “Teenager” that will take the age of a person and return true if is a teenager and false if not. A teenager is someone who is between 12 and 18 years old. Write a function “Teenager” that will take the age of a person and return true if is a teenager and false if not. A teenager is someone who is between 12 and 18 years old.

30 Exercise 8 Write a function “PI” that will return the value of π which is Write a function “PI” that will return the value of π which is

31 Exercise 9 Write a function “Decimal” that will return the decimal part of a number. Write a function “Decimal” that will return the decimal part of a number.Example: Given the number the function will return the value Given the number the function will return the value Hint: = 0.46 Hint: = 0.46 num int(num)

32 Exercise Write a function “Power” to calculate the power of a given number. i.e. Power(2,3) = 2 3 = 8 Power(4,2) = 4 2 = Write a function “Equation” to calculate the equation 3x 3 9x 5. x is a value formal parameter. 3. Using the function “Equation” write a program to calculate and display the equation 3  6 3  9  6 5.

33 What is the output of the following program? What is the output of the following program? Exercise 11 #include using namespace std; int StopAt(int i, int m, int n) { if (2*m-1 <= n) return i – 1; else return n – i; } void display(int n, char c) { int i, j; for (i = 1; i <= n; i++) { for (j = 1; j <= StopAt(i,i,n); j++) cout << ' '; cout << c; if (i*2-1 != n) { for (j = 1; j <= StopAt((2*i)%(n+1),n-i+1,n); j++) cout << ' '; cout << c; } cout << endl; } void main() { display(5,'+'); display(7,'?'); display(6,'0'); }

34 Exercise 12 Write a float function “harmonic” that will take an integer numbers n and return the harmonic series of n which is given by Write a float function “harmonic” that will take an integer numbers n and return the harmonic series of n which is given by

35 Exercise 13 Write a float function “f” that will take an integer numbers n and return the following series: Write a float function “f” that will take an integer numbers n and return the following series:

36 Exercise 14 #include using namespace std; void test(int *&a, int *&b) { int *c = a; a = b; b = c; } void main() { int *p = new int(8); int *r = new int(5); test(p, r); cout << *p << endl << *r; } What is the output of the following program? What is the output of the following program?

Function Templates Special functions that can operate with generic types. Special functions that can operate with generic types. Their functionality can be adapted to more than one type or class without repeating code for each type. Their functionality can be adapted to more than one type or class without repeating code for each type. In C++ this can be achieved using template parameters. In C++ this can be achieved using template parameters. 37

Template Parameters A template parameter is a special kind of parameter that can be used to pass a data-type as argument to a function. A template parameter is a special kind of parameter that can be used to pass a data-type as argument to a function. The format for declaring function templates with type parameters is: The format for declaring function templates with type parameters is: The keywords class and typename have exactly the same meaning and behave exactly the same way. The keywords class and typename have exactly the same meaning and behave exactly the same way. 38 template function declaration;

Function Templates The function GetMax has myType as its template parameter. myType represents a parameter that has not yet been specified but can be used as if it is a regular data-type. The function GetMax has myType as its template parameter. myType represents a parameter that has not yet been specified but can be used as if it is a regular data-type. Function Call: GetMax (4, 12); GetMax (4, 12); GetMax (2.56, 9.002); GetMax (2.56, 9.002); 39 template myType GetMax(myType a, myType b) { return (a>b?a:b); }

Function Templates – Example 40 #include using namespace std; template T GetMax(T a, T b) { T result; result = (a>b?a:b); return result; } int main() { double f = 5.87; cout (4,9) << endl; cout (f,3.14) << endl; cout (’A’,’Z’) << endl; return 0; } Can also declare new objects of type T 95.87Z

Without Specifying Template Type 41 #include using namespace std; template T GetMax(T a, T b) { return (a>b?a:b); } int main() { int a=4, b=8; float x=5.87, y=2.146; cout << GetMax(a,b) << endl; cout << GetMax(x,y) << endl; return 0; } Notice that the GetMax is called without explicitly specifying the data-type. The compiler automatically determines the appropriate instantiation from the arguments passed to the function. Notice that the GetMax is called without explicitly specifying the data-type. The compiler automatically determines the appropriate instantiation from the arguments passed to the function.

Passing Different Data-Types 42 template T GetMax(T a, T b) { return (a>b?a:b); } Error: int a = 8; long b = 10; k = GetMax(a,b);

Multi-Template parameters 43 template T GetMax(T a, U b) { return (a>b?a:b); } Correct: int a = 8; long k, b = 10; k = GetMax (b,a); Correct: int a = 8; long k, b = 10; k = GetMax(b,a);

Namespaces 44 namespace myGlobals { int a, b = 6; } namespace identifier { entities } Namespaces allow to group entities like classes, objects and functions under a name. This way the global scope can be divided into “sub- scopes”, each one with its own name. Namespaces allow to group entities like classes, objects and functions under a name. This way the global scope can be divided into “sub- scopes”, each one with its own name. Format: Format : Example: Example : Variables a and b are normal variables declared within a namespace. They can be accessed using the scope operator ::, i.e. Variables a and b are normal variables declared within a namespace. They can be accessed using the scope operator ::, i.e. myGlobals::a myGlobals::b

Namespaces – Example 1 45 #include using namespace std; namespace myGlobals { int a, b = 6; } int main() { myGlobals::a = 23; cout << myGlobals::a << endl; cout << myGlobals::b << endl; return 0; } 236

Namespaces – Example 2 46 #include using namespace std; namespace first { int var = 5; } namespace second { double var = ; } int main() { cout << first::var << endl; cout << second::var << endl; return 0; }

The Keyword “using” 47 #include using namespace std; namespace first { int x = 5, y = 12; } namespace second { double x = , y = 2.718; } int main() { using first::x; using second::y; cout << x << endl; cout << y << endl; cout << first::y << endl; cout << second::x << endl; return 0; } The keyword “using” is used to introduce a name from a namespace into the current declarative region. The keyword “using” is used to introduce a name from a namespace into the current declarative region.

The Keywords “using namespace” 48 #include using namespace std; namespace first { int x = 5, y = 12; } namespace second { double x = , y = 2.718; } int main() { using namespace first; cout << x << endl; cout << y << endl; cout << second::x << endl; cout << second::y << endl; return 0; } The keyword “using” can also be used as a directive to introduce an entire namespace. The keyword “using” can also be used as a directive to introduce an entire namespace.

The Keywords “using namespace” 49 #include using namespace std; namespace first { int x = 5; } namespace second { double x = ; } int main() { using namespace first; using namespace second; cout << x << endl; return 0; } Ambiguous Identifier #include using namespace std; namespace first { int x = 5; } namespace second { double x = ; } int main() { using namespace first; using namespace second; cout << first::x << endl; return 0; } Error:Correct: 5

The Keywords “using namespace” 50 #include using namespace std; namespace first { int x = 5; } namespace second { double x = ; } int main() { using namespace first; cout << x << endl; } { using namespace second; cout << x << endl; } return 0; } Correct:

Namespace Alias 51 #include using namespace std; namespace myGlobals { int a = 6; } int main() { namespace Num = myGlobals; Num::a = 199; cout << myGlobals::a << endl; return 0; } 199 Alternative names for existing namespaces can be declared as: Alternative names for existing namespaces can be declared as: namespace new_name = current_name;

The “std” Namespace 52 #include namespace myPrint = std; int main() { myPrint::cout << ”Hello world” << myprint::endl; return 0; } All the files in the C++ standard library declare all of its entities within the std namespace. That is why the “using namespace std” statement is generally included in all programs that use any entity defined in iostream. All the files in the C++ standard library declare all of its entities within the std namespace. That is why the “using namespace std” statement is generally included in all programs that use any entity defined in iostream. #include namespace myPrint = std; using namespace myPrint; int main() { cout << ”Hello world” << endl; return 0; }

Functions as parameters to Functions Pointers to functions can also be passed as parameters to another function. Pointers to functions can also be passed as parameters to another function. 53 #include using namespace std; void myFunction(void (*f)(int), int); // Prototype void print(int); // Prototype int main() { myFunction(print, 5); return 0; } void myFunction(void (*f)(int), int n) { for (int i=1; i<=n; i++) (*f)(i); } void print(int x) { cout << x << endl; } 12345

Functions as parameters – Example 54 #include using namespace std; int MinMax(bool (*f)(int&, int&), int A[], int n) { int val = A[0]; for (int i=1; i<n; i++) if ((*f)(A[i],val)) val = A[i]; return val; } bool Min(int &x, int &y) { return x < y; } bool Max(int &x, int &y) { return x > y; } int main() { int values[] = {4,7,5,2,9,3}; cout << ”Smallest = ” << MinMax(Min,values,6) << endl; cout << ”Biggest = ” << MinMax(Max,values,6) << endl; return 0; } Smallest = 2 Biggest = 9