Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Programming Principles II Lecture Notes 4 Functions (Returning Values) Andreas Savva."— Presentation transcript:

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

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

3 3 Functions Function None or many inputparameters Exactly one return value

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

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

6 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 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 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 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 7 9 8 6

10 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 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 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 = 1 + 6 * MySqr(4); } Does not return a value Returns

13 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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) = 1 + 2 + 3 + 4 = 10 Sum(1,4) = 1 + 2 + 3 + 4 = 10 Sum(4,9) = 4 + 5 + 6 + 7 + 8 + 9 = 39 Sum(4,9) = 4 + 5 + 6 + 7 + 8 + 9 = 39 Sum(7,7) = 7 Sum(7,7) = 7 Sum(7,2) = 0 Sum(7,2) = 0

28 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 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 30 Exercise 8 Write a function “PI” that will return the value of π which is 3.14159. Write a function “PI” that will return the value of π which is 3.14159.

31 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 13.46 the function will return the value 0.46. Given the number 13.46 the function will return the value 0.46. Hint: 13.46 - 13 = 0.46 Hint: 13.46 - 13 = 0.46 num int(num)

32 32 Exercise 10 1. 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 = 16 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 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 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 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 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?

37 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

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

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

40 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

41 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; } 85.87 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.

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

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

44 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

45 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

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

47 The Keyword “using” 47 #include using namespace std; namespace first { int x = 5, y = 12; } namespace second { double x = 3.14159, 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; } 52.718123.14159 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.

48 The Keywords “using namespace” 48 #include using namespace std; namespace first { int x = 5, y = 12; } namespace second { double x = 3.14159, y = 2.718; } int main() { using namespace first; cout << x << endl; cout << y << endl; cout << second::x << endl; cout << second::y << endl; return 0; } 5123.141592.718 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.

49 The Keywords “using namespace” 49 #include using namespace std; namespace first { int x = 5; } namespace second { double x = 3.14159; } 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 = 3.14159; } int main() { using namespace first; using namespace second; cout << first::x << endl; return 0; } Error:Correct: 5

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

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

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

53 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

54 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


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

Similar presentations


Ads by Google