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 doubles. 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
#include<iostream> using namespace std; Double larger ( double x , double y )‏ { double max; if ( x >= y )‏ max = x; else max = y; return max; } int main ( )‏ cout << “The larger of 5 and 6 is “ << larger(5 , 6) << endl; //Function Call return 0; 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; //Function Call return 0; Solution Ex 2

13 Example: Without return value
#include<iostream> using namespace std; 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; } int main ( )‏ number_type( 5 ); //Function Call return 0; Solution Ex 3

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

15 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

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

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

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

19 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

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

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

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

23 Scope of variables

24 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

25

26 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

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

28 Global VS Local variables
#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 I is 5 I is 100 I is 5

29 Scope of Local Variables, cont.

30 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

31 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

32 I. Using Global Variables
#include <iostream> using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; }

33 I. Using Global Variables
#include <iostream> using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x

34 I. Using Global Variables
#include <iostream> using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x void main() { f2(); cout << x << endl ; } 1

35 I. Using Global Variables
#include <iostream> using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 4 void f2() { x += 4; f1(); } 2 void main() { f2(); cout << x << endl ; } 1

36 I. Using Global Variables
#include <iostream> using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 5 4 void f1() { x++; } 4 void f2() { x += 4; f1(); } 3 void main() { f2(); cout << x << endl ; } 1

37 I. Using Global Variables
#include <iostream> using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 5 4 void f1() { x++; } 5 void f2() { x += 4; f1(); } 3 void main() { f2(); cout << x << endl; } 1

38 I. Using Global Variables
#include <iostream> using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 5 4 void f2() { x += 4; f1(); } 6 void main() { f2(); cout << x << endl; } 1

39 I. Using Global Variables
#include <iostream> using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 4 5 void main() { f2(); cout << x << endl; } 7

40 I. Using Global Variables
#include <iostream> using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 4 5 void main() { f2(); cout << x << endl; } 8

41 I. Using Global Variables
#include <iostream> using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; }

42 What is Bad About Using Global Vairables?
Not safe! If two or more programmers are working together in a program, one of them may change the value stored in the global variable without telling the others who may depend in their calculation on the old stored value! Against The Principle of Information Hiding! Exposing the global variables to all functions is against the principle of information hiding since this gives all functions the freedom to change the values stored in the global variables at any time (unsafe!)

43 Local Variables Local variables are declared inside the function body and exist as long as the function is running and destroyed when the function exit You have to initialize the local variable before using it If a function defines a local variable and there was a global variable with the same name, the function uses its local variable instead of using the global variable

44 Example of Defining and Using Global and Local Variables
#include <iostream> using namespace std; int x; // Global variable Void fun(); // function prototype void main() { x = 4; fun(); cout << x << endl; } void fun() int x = 10; // Local variable

45 Example of Defining and Using Global and Local Variables
#include <iostream> using namespace std; int x; // Global variable Void fun(); // function prototype void main() { x = 4; fun(); cout << x << endl; } void fun() int x = 10; // Local variable x Global variables are automatically initialized to 0

46 Example of Defining and Using Global and Local Variables
#include <iostream> using namespace std; int x; // Global variable Void fun(); // function prototype void main() { x = 4; fun(); cout << x << endl; } void fun() int x = 10; // Local variable x void main() { x = 4; fun(); cout << x << endl; } 1

47 Example of Defining and Using Global and Local Variables
#include <iostream> using namespace std; int x; // Global variable Void fun(); // function prototype void main() { x = 4; fun(); cout << x << endl; } void fun() int x = 10; // Local variable x 4 void fun() { int x = 10; cout << x << endl; } x ???? 3 void main() { x = 4; fun(); cout << x << endl; } 2

48 Example of Defining and Using Global and Local Variables
#include <iostream> using namespace std; int x; // Global variable Void fun(); // function prototype void main() { x = 4; fun(); cout << x << endl; } void fun() int x = 10; // Local variable x 4 void fun() { int x = 10; cout << x << endl; } x 10 3 void main() { x = 4; fun(); cout << x << endl; } 2

49 Example of Defining and Using Global and Local Variables
#include <iostream> using namespace std; int x; // Global variable Void fun(); // function prototype void main() { x = 4; fun(); cout << x << endl; } void fun() int x = 10; // Local variable x 4 void fun() { int x = 10; cout << x << endl; } x 10 4 void main() { x = 4; fun(); cout << x << endl; } 2

50 Example of Defining and Using Global and Local Variables
#include <iostream> using namespace std; int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() int x = 10; // Local variable x 4 void fun() { int x = 10; cout << x << endl; } x 10 5 void main() { x = 4; fun(); cout << x << endl; } 2

51 Example of Defining and Using Global and Local Variables
#include <iostream> using namespace std; int x; // Global variable Void fun(); // function prototype void main() { x = 4; fun(); cout << x << endl; } void fun() int x = 10; // Local variable x 4 void main() { x = 4; fun(); cout << x << endl; } 6

52 Example of Defining and Using Global and Local Variables
#include <iostream> using namespace std; int x; // Global variable Void fun(); // function prototype void main() { x = 4; fun(); cout << x << endl; } void fun() int x = 10; // Local variable x 4 void main() { x = 4; fun(); cout << x << endl; } 7

53 Example of Using Value Parameters and Global Variables
#include <iostream> using namespace std; int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() x = 4; fun(x/2+1); x void main() { x = 4; fun(x/2+1); cout << x << endl; } 1

54 Example of Using Value Parameters and Global Variables
#include <iostream> using namespace std; int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() x = 4; fun(x/2+1); x 4 void fun(int x ) { cout << x << endl; x=x+5; } 3 void main() { x = 4; fun(x/2+1); cout << x << endl; } 3 2

55 Example of Using Value Parameters and Global Variables
#include <iostream> using namespace std; int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() x = 4; fun(x/2+1); x 4 void fun(int x ) { cout << x << endl; x=x+5; } 3 8 4 void main() { x = 4; fun(x/2+1); cout << x << endl; } 2

56 Example of Using Value Parameters and Global Variables
#include <iostream> using namespace std; int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() x = 4; fun(x/2+1); x 4 void fun(int x ) { cout << x << endl; x=x+5; } 8 3 5 void main() { x = 4; fun(x/2+1); cout << x << endl; } 2

57 Example of Using Value Parameters and Global Variables
#include <iostream> using namespace std; int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() x = 4; fun(x/2+1); x 4 void main() { x = 4; fun(x/2+1); cout << x << endl; } 6

58 Example of Using Value Parameters and Global Variables
#include <iostream> using namespace std; int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() x = 4; fun(x/2+1); x 4 void main() { x = 4; fun(x/2+1); cout << x << endl; } 7

59 Methods of Passing

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

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

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

63 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.

64 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!

65 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

66 Cont. Example 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!

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

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

69 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

70 Passing arguments by reference
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;

71 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 pass by CONST reference to avoid unintentional changes. We can return multiple values from a function.

72 Function Overloading

73 Function Overloading Two or more functions can have the same name but different parameters Example: int max(int a, int b) { if (a>= b) return a; else return b; } float max(float a, float b) { if (a>= b) return a; else return b; }

74 Function Overloading In a C++ program, several functions can have the same name This is called function overloading or overloading a function name

75 Function Overloading (continued)
Two functions are said to have different formal parameter lists if both functions have: A different number of formal parameters, or If the number of formal parameters is the same, then the data type of the formal parameters, in the order you list them, must differ in at least one position

76 The functions functionSix and functionSeven both have three formal parameters and the data type of the corresponding parameters is the same; therefore, these functions have the same formal parameter list

77 Function Overloading (continued)
Function overloading: creating several functions with the same name The signature of a function consists of the function name and its formal parameter list Two functions have different signatures if they have either different names or different formal parameter lists Note that the signature of a function does not include the return type of the function

78 These function headings correctly overload the function functionXYZ:
Both of these function headings have the same name and same formal parameter list Therefore, these function headings to overload the function functionABC are incorrect In this case, the compiler will generate a syntax error Note that the return types of these function headings are different

79 Functions with Default Parameters
When a function is called The number of actual and formal parameters must be the same C++ relaxes this condition for functions with default parameters You specify the value of a default parameter when the function name appears for the first time, such as in the prototype

80 Functions with Default Parameters (continued)
If you do not specify the value of a default parameter The default value is used All of the default parameters must be the rightmost parameters of the function In a function call where the function has more than one default parameter and a value to a default parameter is not specified You must omit all of the arguments to its right

81 Functions with Default Parameters (continued)
Default values can be constants, global variables, or function calls The caller has the option of specifying a value other than the default for any default parameter You cannot assign a constant value as a default value to a reference parameter

82

83

84 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

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

86 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";; }

87 By: Nouf Almunyif Recursion

88 Recursion and Recursive Functions
Main calls another function…..normal A function calls another function2….normal A function calls itself ?! Possible?? YES A recursive function is one that call itself.

89 General form void recurse() { recurse(); //Function calls itself }

90 Finding Factorial 5! = 5*4*3*2*1
Final value=120 5!=5*24=120 returned 5*4! 5*4! 4!=4*6=24 returned 4*3! 4*3! 3!=3*2=6 returned 3*2! 3*2! 2!=2*1=2 returned 2*1! 2*1! 1 1 1

91 Finding Factorial #incloud <iostream>; Using nampespace std;
Void main() { int n,factorial,i; cout << "Enter a positive integer: "; cin >> n; for (i = 1; i <= n; i++) { if (i == 1) factorial = 1; Else factorial = factorial * i; } cout << "The factorial of " << n << " is " << factorial << endl;

92 Finding Factorial Recursively
Enter a positive integer : 4 //Recursive factorial Function #include<iostream> Int factorial(int N); Void main() { int num; cout<<“Enter a positive integer:”; cin>>num; cout<<“factorial=“<<factorial(num); } Int factorial( int N) { if ( N <= 1) //the base case return 1; else return N * factorial (N - 1); Factorial = 24 N=4 Retrun 4 *factorial(3) 6 4*6=24 N=3 Retrun 3 *factorial(2) 2 3*2 =6 N=2 Retrun 2 *factorial(1) 2*1 = 2 1 N=1 Retrun 1

93 Example printing number counting down
 void main() { int input; cout<<"enter positive number "; cin>>input; myMethod(input);   } #include <iostream> using namespace std; void myMethod( int counter) { if(counter == 0) return; // no value returning just for EXIT the function else { cout<<counter<<endl; myMethod(--counter); }


Download ppt "CSC1201: Programming Language 2"

Similar presentations


Ads by Google