Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC1201: Programming Language 2

Similar presentations


Presentation on theme: "CSC1201: Programming Language 2"— Presentation transcript:

1 CSC1201: Programming Language 2
Functions

2 – Organize code in program – Code are easier to maintain?
A Function is a group of statements that together perform a task. It can be used anywhere in the program. Why we need function? – Organize code in program – Code are easier to maintain? Function declaration: return_type FuncName(Type arg1, Type arg2,….. Type argN) { function body } A program can contain one or many functions Must always have a function called “main”. The main function is the starting point of all C++ programs The compiler will not compile the code unless it finds a function called “main” within the program.

3 “Hello World” program #include <iostream> using namespace std; int main ()‏ { cout << “Hello World\n”; Return 0; }

4 Function When we need function? – When you need to repeat the same process over and over in a program. – The function can be called many times but appears in the code once.

5 1- Predefined functions
Predefined functions are functions that are built into C++ Language to perform some standard operations. The C++ standard library provides numerous built- in functions that your program can call. For example, function strcat() to concatenate two strings the definitions have been written and it is ready to be used. – User needs to include pre-defined header file (i.e. math.h, time.h)

6 2- User defined functions
Function that been created by the user. – This functions need to be declared and defined by the user

7 functions Value returning functions: Void functions:
functions that have a return type. These functions return a value of a specific data type using the return statement. Void functions: functions that do not have a return type. These functions do not use a return statement to return a value.

8 Value returning functions
The syntax is: FuncType FuncName(formal parameter list )‏ { statements }

9 Void functions The syntax is: Void FuncName ( formal parameter list )‏
{ statements }

10 Examples: Write a Function larger, which returns the larger of the two given integers. Write a Function Square, which returns the square of the given integer. Write a function number_type. The function should output the number and message saying whether the number is positive, negative, or zero.

11 Example: With return value
Double larger ( double x , double y )‏ { double max; if ( x >= y )‏ max = x; else max = y; return max; } Function Call …….. Cout << “The larger of 5 and 6 is “ << larger(5 , 6) << endl; ………. Solution Ex 1

12 Example: With return value
#include<iostream> using std::cin; using std::cout; using std::endl; int square (int x)‏ { return x*x; } int main ( )‏ int number; cout<<"Enter any number to Calculate the square of this number "; cin>>number; cout<<endl; cout<<"the square of "<<number<<" is " <<square(number)<<endl; return 0; Solution Ex 2

13 Example: Without return value
Void number_type ( int x)‏ { if ( x > 0 )‏ cout << x << “ is positive.” << endl; else if ( x < 0 )‏ cout << x << “ is negative.” << endl; else cout<< x << “is a zero.”<<endl; } Function Call …….. Number_type( 5 ); ………. Solution Ex 3

14 Scope of variables

15 C++ Variables A variable is a place in memory that has
A name or identifier (e.g. income, taxes, etc.) A data type (e.g. int, double, char, etc.) A size (number of bytes) A scope (the part of the program code that can use it) Global variables – all functions can see it and using it Local variables – only the function that declare local variables see and use these variables A life time (the duration of its existence) Global variables can live as long as the program is executed Local variables are lived only when the functions that define these variables are executed

16

17 Global VS Local variables
Variables that declared inside a function Declared inside any block of code Global variables Opposite of local the known throughout the entire program

18 Global VS Local variables
#include < iostream> Using namespace std;

19 Global VS Local variables
I is 5 I is 100 I is 5 #include < iostream> Using namespace std; void main() { int i=4; int j=10; i++; if (j > 0) cout<<“ i is “<<i<<endl; { int i=100; /* 'i' is defined and so local to * this block */ Cout << "i is” << i; } //end if cout<<"i is “<<i; } //end main

20 Scope of Local Variables, cont.

21 Variable Scope In fact, you can reuse names in a scope which is nested inside another scope int main ( ) { int i = 5, j = 0; for (j = 0; j < 10; j++) { int i = j; // OK, this is new i int k = 5; doSomething (i); } int sum = k; // compile error, no k in scope j = i; // sets j to 5 for (j = 0; j < 100; j++ ) { int i = j; // yet another new i int i = 0; // compile error –redefined variable void doSomething(int i){ cout<<++i;}// OK, this is new i

22 Variable Scope Local variables of same name can be nested inside global variables #include<iostream> using namespace std; int i = 10; int main ( ) { cout<<i<<endl;//10 for (int j = 0; j < 10; j++ ) { int i = 20; cout<<i<<endl;//20 } int i = 30; cout<<i<<endl;//30 return 0;} int total = 5; int main ( ) { int total = 4; // OK, this is nested scope …. } int sub1 ( ) { int i = total; // OK, i set to 5

23 Function The function are reusable.
functions may be called Procedures or Routines and in object oriented programming called Methods . Save programmers’ time.

24 Prototype VS. Declaration
prototype : normally placed before the start of main() but must be before the function definition. General form : function_return_type function_name (type parameter1, type parameter2,…, type parameterN) ; EX: void Factorial (int x); // prototype -- x is a parameter

25 Prototype VS. Declaration
void foo(int x); // prototype -- x is a parameter Declaration void foo(int x) // declaration -- x is a parameter { Statement . }

26 EX: #include<iostream> using namespace std; int square (int x)‏ { return x*x; } void main ( )‏ { int number; cout<<"Enter any number to Calculate the square of this number "; cin>>number; cout<<endl; cout<<"the square of "<<number<<" is " <<square(number)<<endl; }

27 EX: #include<iostream> using namespace std; int square (int x)‏ ; Void main ( )‏ { int number; cout<<"Enter any number to Calculate the square of this number "; cin>>number; cout<<endl; cout<<"the square of "<<number<<" is " <<square(number)<<endl; } int square (int x)‏ { return x*x; }

28 Finding Errors in Function Code
int sum(int x, int y) { int result; result = x+y; } this function must return an integer value as indicated in the header definition (return result;) should be added

29 Finding Errors in Function Code
int sum (int n) { if (n==0) return 0; else n+(n-1); } the result of n+sum(n-1) is not returned; sum returns an improper result, the else part should be written as:- else return n+(n-1);

30 Finding Errors in Function Code
void f(float a); { float a; cout<<a<<endl; } ; found after function definition header. redefining the parameter a in the function void f(float a) { float a2 = a + 8.9; cout <<a2<<endl; }

31 Finding Errors in Function Code
void product(void) { int a, b, c, result; cout << “enter three integers:”; cin >> a >> b >> c; result = a*b*c; cout << “Result is” << result; return result; } According to the definition it should not return a value , but in the block (body) it did & this is WRONG.  Remove return Result;

32 Parameters vs Arguments
Up until now, we have not differentiated between function parameters and arguments. In common usage, the terms parameter and argument are often interchanged. A function parameter is a variable declared in the prototype or declaration of  An argument is the value that is passed to the function in place of a parameter.

33 methods of passing There are 2 primary methods of passing arguments to functions: pass by value, pass by reference,

34 Passing arguments by value
void foo(int y) {        cout << "y = " << y << endl; } int main()     foo(5); // first call     int x = 6;     foo(x); // second call     foo(x+1); // third call     return 0; By default, arguments in C++ are passed by value. When arguments are passed by value, a copy of the argument is passed to the function.

35 Passing arguments by value
void foo(int y) {     cout << "y = " << y << endl;     y = 6; } // y is destroyed here int main()     using namespace std;     int x = 5;     cout << "x = " << x << endl;     foo(x);     return 0; } Because a copy of the argument is passed to the function, the original argument can not be modified by the function.

36 Adv. And DisAdv. Of Passing by value
Advantages Disadvantages Arguments passed by value can be: variables (eg. x), literals (eg. 6), or expressions (eg. x+1) or (eg foo()). Arguments are never changed by the function being called, which prevents side effects. Copying large structs or classes can take a lot of time to copy, and this can cause a performance penalty, especially if the function is called many times.

37 Absolute value #include <iostream> using namespace std;
int absolute (int);// function prototype for absolute() int main(){ int num, answer; cout << "Enter an integer (0 to stop): "; cin >> num; while (num!=0){ answer = absolute(num); cout << "The absolute value of " << num << " is: " << answer << endl; cin >> num; } return 0; } // Define a function to take absolute value of an integer int absolute(int x){ if (x >= 0) return x; else return -x; }

38 methods of passing There are 2 primary methods of passing arguments to functions: pass by value, pass by reference,

39 Passing arguments by reference
When passing arguments by value, the only way to return a value back to the caller is via the function’s return value. While this is suitable in many cases, there are a few cases where better options are available.

40 Passing arguments by reference
In pass by reference, we declare the function parameters as references rather than normal variables: 1 2 3 4 void AddOne(int &y) // y is a reference variable {     y = y + 1; } When the function is called, y will become a reference to the argument. The reference to a variable is treated exactly the same as the variable itself. any changes made to the reference are passed through to the argument!

41 Passing arguments by reference
Sometimes we need a function to return multiple values. However, functions can only have one return value. One way to return multiple values is using reference parameters

42 Cont. Example 1 void foo(int &y) // y is now a reference {     cout << "y = " << y << endl;     y = 6; } // y is destroyed here int main()     int x = 5;     cout << "x = " << x << endl;     foo(x);     return 0; } This program is the same as the one we used for the pass by value example, except foo’s parameter is now a reference instead of a normal variable. When we call foo(x), y becomes a reference to x. Note that the value of x was changed by the function!

43 Passing arguments by reference
Example 2 void AddOne(int &y) {     y++; } int main()     int x = 1;     cout << "x = " << x << endl;     AddOne(x);     return 0;

44 Passing arguments by reference
Example 3 #include <iostream> Using namespace std ; Void duplicate (int& a, int& b, int & c); Void main () { Int x=1,y=3,z=7; Duplicate (x,y,z); Cout << “x=“<<x<<“, y=“<<y<<“,z=“<<z; } Void duplicate (int& a, int& b, int & c) { a*=2; b*=2; c*=2;

45 Passing arguments by reference
#include <iostream> Using namespace std ; void swap(float &x, float &y); int main() { float a, b; cout << "Enter 2 numbers: " << endl; cin >> a >> b; if(a>b) swap(a,b); cout << "Sorted numbers: "; cout << a << " " << b << endl; return 0; } void swap(float &x, float &y) { float temp; temp = x; x = y; y = temp; } Example 4

46 Passing arguments by reference
Example 5 1 #include <iostream> #include <math.h>    // for sin() and cos() Using namespace std; void GetSinCos(double dX, double &dSin, double &dCos) {     dSin = sin(dX);     dCos = cos(dX); } int main()     double dSin = 0.0;     double dCos = 0.0;       GetSinCos(30.0, dSin, dCos);    cout << "The sin is " << dSin << endl;    cout << "The cos is " << dCos << endl;     return 0;

47 Advantages of passing by reference
It allows us to have the function change the value of the argument, which is sometimes useful. Because a copy of the argument is not made, it is fast, even when used with large structus or classes. We can return multiple values from a function.

48 Function Overloading Function overloading
Functions with same name and different parameters or return data type Should perform similar tasks I.e., function to square ints and function to square floats int square( int x) {return x * x;} float square(float x) { return x * x; } A call-time c++ complier selects the proper function by examining the number, type and order of the parameters

49 Function overloading Example
cout << "Enter Fahrenheit temperature: "; switch (level)‏ { case 1 : cin >> inttemp; FtoC(inttemp); break; case 2 : cin >> floattemp; FtoC(floattemp); case 3 : cin >> doubletemp; FtoC(doubletemp); default : cout << "Invalid selection\n"; } return 0; #include <iostream> using namespace std; void FtoC(int temp); void FtoC(float temp); void FtoC(double temp); int main()‏ { int inttemp, level; float floattemp; double doubletemp; cout << "CONVERTING FAHRENHEIT TO CELSIUS\n"; cout << "Select required level of precision\n"; cout << "Integer (1) - Float (2) - Double (3)\n"; cin >> level;

50 Function overloading Cont.
void FtoC( int itemp)‏ { int temp = (itemp - 32) * 5 / 9; cout << "Integer precision: "; cout << itemp << "F is " << temp << "C\n"; } void FtoC( float ftemp)‏ float temp = (ftemp - 32) * 5.0 / 9.0; cout << "Float precision: "; cout << ftemp << "F is " << temp << "C\n";; void FtoC( double dtemp)‏ { double temp = (dtemp - 32) * 5.0 / 9.0; cout << "Double precision : "; cout << dtemp << "F is " << temp << "C\n";; }


Download ppt "CSC1201: Programming Language 2"

Similar presentations


Ads by Google