html5-img
1 / 75

Functions

Functions. Outlines. Advantage of Functions (divide and conquer) Standard Library Functions (Pre-defined functions ) Programmer (User) Defined Functions Local and Global Variables Scope of Variables Functions with no types (void functions) Arrays and Functions

mead
Download Presentation

Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Functions

  2. Outlines • Advantage of Functions (divide and conquer) • Standard Library Functions (Pre-defined functions ) • Programmer (User) Defined Functions • Local and Global Variables • Scope of Variables • Functions with no types (void functions) • Arrays and Functions • Arguments passing by value and by reference • Default values in arguments • Function overloading • Recursion • Prototyping function

  3. Introduction • Most useful programs are much larger than the programs that we have considered so far • To make large programs manageable, programmers modularize them into subprograms. • These subprograms are called functions. • They can be compiled and tested separately and reused in different programs • Rather than code one long program, write several smaller routines, called functions. One of those functions must be called main(). The main() function is always the first to execute. It doesn’t have to be first in a program

  4. Functions • The best way to develop and maintain large program is to construct from small, simple pieces or components • The technique is called modular programming or divide and conquer • Advantages of Functions • Helps to write modular program • A modular program can be easily understood by the reader of the programs and hence easy to debug, trace and fix • Functions can be reused in different programs which helps to minimize errors in a program as the functions reused are well tested by other programmers

  5. Functions • General Form/Syntax Ret_Typefunction_Name(Parameter_list) { //body of the function } • Ret_Type: specifies the data type to be returned by the function • function_Name: valid identifier name Alphabet|Underscore + Digit + … • Parameter_list: comma separated list of variables • The parenthesis () are required even if the parameter list is empty

  6. Cont’d… • Example: • int a, b, c; // Three variables of type int • float add; // a floating point variable • int add( int a, int b); // function with two parameters • float mult( float x, y); // incorrect funtion declaration, why? • double balance(); // empty parameter list • return type is double • void print(); // does not return a value to the caller

  7. Two type of functions • Standard library functions • Predefined functions • User defined functions • The most common once • Defined by the programmer or user

  8. STANDARD C++ LIBRARY FUNCTIONS • Also called built-in functions or predefined functions as they are brought with the C++ compiler • Functions defined in math.h • sqrt(), pow(x,y), log10(x), log(x), abs(x), sin(t), cos(t), … • Functions defined in conio.h • clrscr(), getch() • Functions defined in stdlib.h • rand(), • Functions defined in string.h • Strcpy(s1,s2), strcmp(s1,s2), strlen(str)

  9. (Library functions) Cont’d… • An example of functions belonging to math.h, stdlib.h, conio.h, iostream.h // LibFunc.cpp, an example #include<iostream.h> #include<math.h> #include<stdlib.h> #include<conio.h> #include<iomanip.h>

  10. // LibFunc.cpp, an example Cont’d… void main() { for(int x=0;x<=10; x++) cout<<"\n sqrt{"<<x<<") = "<<sqrt(x); int a=3, b=-4; b = abs(b); cout<<"\n b = "<<b; cout<<"\n pow(a, b)="<<pow(a,b); cout<<"\n log(2.71828)= "<<log(2.71828); cout<<endl; for(inti=0;i<15; i++) cout<<(rand() % 15 + 1)<<setw(5); cout<<endl; cout<<endl; for(inti=0;i<10; i++) cout<<(rand() % 10)<<"\t"; cout<<endl; for(inti=0;i<10; i++) cout<<(rand() % 10)<<"\t"; cout<<endl; for(inti=0;i<10; i++) cout<<(rand() % 10)<<"\t"; getch(); }

  11. Cont’d… Output of LibFunc.cpp sqrt{0) = 0 sqrt{1) = 1 sqrt{2) = 1.41421 sqrt{3) = 1.73205 sqrt{4) = 2 sqrt{5) = 2.23607 sqrt{6) = 2.44949 sqrt{7) = 2.64575 sqrt{8) = 2.82843 sqrt{9) = 3 sqrt{10) = 3.16228 b = 4 pow(a, b)=81 log(2.71828)= 0.999999 2 11 3 11 2 8 1 11 14 2 5 9 2 5 13 0 2 1 3 7 9 1 0 5 4 9 2 1 9 6 1 1 5 3 4 0 9 5 1 2 9 8 6 4 2

  12. USER-DEFINED FUNCTIONS • Programmers also need to be able to define their own functions • C++ functions generally adhere to the following rules • Every function must have a name • Function names are variable names and can contain up to 32 characters, they must begin with a letter, and they can consist of letters, numbers, and the underscore (_) character • All function names have one set of parentheses immediately following them, which helps to differentiate them from variables. • Ex: void print() , int cube(x)

  13. Cont’d… • The body of each function, starting immediately after the closing parenthesis of the function name, must be enclosed by braces • Recommended that • One better use meaningful function names. Calc_balance() is more descriptive than xy3(). Syntax: Return_TypeFunction_Name(Parameter List) { // body of the function }

  14. User Defined Functions…. //cube.cpp #include<iostream.h> #include<conio.h> int cube(int x) { // returns cube of x: return x*x*x; } void main () { int a; cout<<"\n Enter a number to find its cube: "; cin>>a; cout<<endl; cout<<a<<" cubed = "<<cube(a)<<endl; cout<<endl; for(inti=1;i<=5;i++) cout<<i<<" cubed = "<<cube(i)<<endl; getch(); } Main() cube() 5 a int x int 5 5 125

  15. void main( ) int a cube ( a ) Argument passing int cube(x) Function call Return type

  16. Function, Example: Circle.cpp Sample Run Enter the radius: 10 Area = 314.159 Circumference = 62.8318 #include<iostream.h> #include<conio.h> const float pi = 3.14159; float area(float x) { return pi*x*x; } float circumference(float x) { return 2*pi*x; } void main () { float r; cout<<"\n Enter the radius: "; cin>>r; cout<<"\n Area = "<<area(r); cout<<"\n Circumference = "<<circumference(r); getch(); }

  17. Cont’d… #include<iostream.h> #include<conio.h> const float rate = 0.08; float balance(float x) { float bal = x + x*rate; return bal; } void main () { float amount; cout<<"\n Enter the amount: "; cin>>amount; cout<<"\n Balance = "<<balance(amount); getch(); }

  18. Cont’d… • Exercise • Temperature conversion from degree Celsius to degree Fahrenheit and vice-versa is as shown below • T oC = (T oF - 32 ) * 5/9 • T oF = T oC *9/5 + 32 • Write a function that converts temperature from degree Celsius to degree Fahrenheit • Write a function that converts temperature from degree Fahrenheit to degree Celsius

  19. User Defined Functions… • Assignment(10%) • Write a function that returns • Maximum of three floating point numbers • Minimum of three floating point numbers • Write a program that uses two functions area and perimeter to find area and perimeter of a rectangle • Area = x * y • Perimeter = 2*x*y, where x and y are length and width of the rectangle • Write a program that calculates net salary for a given basic salary by deducting pension and income tax assume the following: • Pension: 6% of basic salary and income tax based on the following rule

  20. Cont’d… Use separate functions to calculate income tax and pension, use the following format if you wish: float incomeTax(float basicSal) { ……. } float pension(float basicSal) { }

  21. Function declaration, Function Definition & Function Call Function Declaration/ Prototype #include<iostream.h> #include<conio.h> void calc_it(int); int main() { calc_it(8); getch(); return 0; } void calc_it(int x) { intsqr; do{ sqr=x * x; cout<<"\n The square of "<<x<<"="<<sqr; x++; }while(sqr<=250); } Function Calls Function Definition

  22. Menu Driven Program #include<iostream.h> #include<conio.h> void compSc() { cout<<"\n Welcome to the Computer Science Dept!"; cout<<"\n An ever growing field of study."; } void Acct() { cout<<"\n Welcome to the Accounting Dept!"; cout<<"\n Learn how to control and make profit from your business."; } void Mgt() { cout<<"\n Welcome to the Management Dept!"; cout<<"\n Learn how to manage your business."; }

  23. Cont’d… void main() { int opt; do { cout<<"\n\n...Main Menu........"; cout<<"\n Computer Science... 1"; cout<<"\n Accounting ........ 2"; cout<<"\n Management ........ 3"; cout<<"\n Quit program....... 4\n"; cout<<"\n Enter your option to view a report: "; cin>>opt; switch(opt) { case 1: compSc(); break; case 2: Acct(); break; case 3: Mgt(); break; case 4: cout<<"\n End of the program!!"; break; } }while(opt !=4); getch(); }

  24. String Functions //stringFunc1.cpp #include <iostream.h> #include <conio.h> #include <stdio.h> int main() { char str[80]; gets(str); cout<<"\n Length is: "<<strlen(str); cout<<endl; char ch[100]; cin.getline(ch, 100,'#'); cout<<ch; cout<<"\n Length is: "<<strlen(ch); getch(); }

  25. String Functions #include <iostream.h> #include <conio.h> #include <ctype.h> char* strFunc(char *c) { int n = strlen(c); for(inti=0; i<n; i++) if(islower(c[i])) c[i]=toupper(c[i]); return c; } void main() { char *ch="Hello World"; cout<<ch; cout<<endl; char *p = strFunc(ch); cout<<p; getch(); }

  26. Local and Global variables • A variable is global if it is defined outside of a function • A variable is local if it is defined in the body of a function • A local variable is simply a variable that is declared inside a block. It is accessible only from within that block. • Since the body of a function itself is a block, variables declared within a function are local to that function; they exist only while the function is executing • Use global variables only sparingly and when only necessary as they can be illegally modified by someone and introduce undesired effect to the program

  27. Global vs Local variables #include<iostream.h> #include<conio.h> const float pi = 3.14159; // Global variable double d; // Global variable float area(float x) { return pi*x*x; } float circumference(float y) { return 2*pi*y; } void main () { float r; // local variable cout<<"\n Enter the radius: "; cin>>r; cout<<"\n Area = "<<area(r); cout<<"\n Circumference = "<<circumference(r); d=2*r; cout<<"\n Diameter of the circle = "<<d; getch(); } x is local to the function area() y is local to the function circumference() r is local to the function main()

  28. Global vs Local variables Q1. Find and list global and local variables in the program Q2. Modify the program to appropriate local variables and function using parameters Illegal modification of salary #include<iostream.h> #include<conio.h> float salary; float tax() { salary = salary-200; float t = salary * 0.15; return t; } float pension() { float p = salary*0.06; return p; } void main () { salary = 1500; float tx=tax(); float pen =pension(); cout<<"\n Tax = "<<tx; cout<<"\n Pension = "<<pen; getch(); } This program shows not only bad use of global variables but also the importance of using local variables

  29. Scope of variables • Scope of variable refers to the function or block in which a variable is accessible or visible • Variable scope protects variables in one function from other functions that might overwrite them • If a function doesn’t need access to a variable, that function shouldn’t be able to see or change the variable • All local variables disappear (lose their definition) when their block ends • Global variables are visible (“known”) from their point of definition to the end of the program • A local variable defined in a block is known only in that block

  30. Global Variables • Global variables have global scope while local variables have local scope // Program that contains two global variables. #include <iostream.h> #include <conio.h> do_fun(); third_fun(); main() { cout <<"No variables defined in main() \n\n"; do_fun(); // Call the first function getch(); return 0; } Prototype of functions to be discussed later.

  31. Cont’d… float sales, profit; // Two global variables. do_fun() { sales = 20000.00; profit = 5000.00; // . cout <<"The sales in the second function are " <<sales <<"\n"; cout <<"The profit in the second function is " <<profit <<"\n\n"; third_fun(); // Call the third function to show that global variables are visible. return 0; } third_fun() { cout <<"In the third function: \n"; cout <<"The sales in the third function are " <<sales <<"\n"; cout <<"The profit in the third function is " <<profit <<"\n"; // If sales and profit were local, they would not be // visible by more than one function. return 0; }

  32. Scope of variables Discuss the scope of each of the variables in the program #include<iostream.h> #include<conio.h> long fact(int n) { // returns n! = n*(n-1)*(n-2)*...*(2)(1) if (n < 0) return 0; else if(n == 0 || n ==1) return 1; long f = 1; while (n > 1) f *= n--; return f; } int main() { // tests the factorial() function: inti; for (i=-1; i < 6; i++) cout << " " << fact(i); getch(); return 0; }

  33. Cont’d… Find out the errors and correct with appropriate local variables Global Variables #include<iostream.h> #include<conio.h> float rate = 0.05; intmyVar = 10; float balance(float x) { float b = x - x*rate; y = 2*y + myVar; amount = 3*amount; return b; } int y =30; void main () { myVar = 2*myVar + 5; cout<<"\n myVar = "<<myVar; float amount =2200; cout<<"\n Balance = "<<balance(amount); b = 5*b+ 100; getch(); }

  34. Scope of variables • Declare all global variables at the top of your program • Local variables are visible and exist only on their block #include<iostream.h> #include<conio.h> int x=20; int main() { int x=5; cout<<" x = "<<x<<endl; { int x=10; cout<<" x = "<<x<<endl; cout<<" ::x = "<<::x<<endl; } cout<<" x = "<<x<<endl; cout<<" ::x = "<<::x<<endl; getch(); return 0; } Scope Resolution operator

  35. Automatic versus Static variables • The terms automatic and static describes what happens to local variables when a function returns to the calling procedure • By default all local variables are automatic i.e. they are erased when their function ends • You can designate a variable as automatic by prefixing its definition with the term auto which is optional • Example main() { inti; auto float x; } Both of the variables are automatic variables

  36. Automatic vs Static variables Output The number 1 multiplied by 3 is 3 Total = 3 The number 2 multiplied by 3 is 6 Total = 6 The number 3 multiplied by 3 is 9 Total = 9 The number 4 multiplied by 3 is 12 Total = 12 The number 5 multiplied by 3 is 15 Total = 15 The number 6 multiplied by 3 is 18 Total = 18 The number 7 multiplied by 3 is 21 Total = 21 The number 8 multiplied by 3 is 24 Total = 24 The number 9 multiplied by 3 is 27 Total = 27 The number 10 multiplied by 3 is 30 Total = 30 #include<iostream.h> #include<conio.h> triple_it(int ); // function prototype void main() { for(intctr=1; ctr<=10; ctr++) triple_it(ctr); getch(); } triple_it(int c) { int total =0, ans; ans = c*3; total +=ans; cout<<"\n The number "<<c<<" multiplied by 3 is "<<ans; cout<<"\n Total = "<<total; return 0; }

  37. Static variables • Static variables are variables that retain their values until the end of the entire program • Declaration proceeded with the static keyword • By default all global variables are static void main() { int a = 15; static x = 25; static y = 30; } Automatic variable Static variables

  38. Automatic vs Static variables #include<iostream.h> #include<conio.h> void f() { static int x=2; int y =5; x = 2*x; y = 3*y; cout<<"x = "<<x<<endl; cout<<"y = "<<y<<endl; } int main() { for(inti = 0; i<3; i++) f(); getch(); return 0; } Output x = 4 y = 15 x = 8 y = 15 x = 16 y = 15

  39. Static variable… #include<iostream.h> #include<conio.h> triple_it(int ); void main() { for(intctr=1;ctr<=10; ctr++) triple_it(ctr); getch(); } triple_it(int c) { static int total =0; intans; ans = c*3; total +=ans; cout<<"\n The number "<<c<<" multiplied by 3 is "<<ans; cout<<"\n Total = "<<total; return 0; } • Output next slide

  40. Cont’d… The number 1 multiplied by 3 is 3 Total = 3 The number 2 multiplied by 3 is 6 Total = 9 The number 3 multiplied by 3 is 9 Total = 18 The number 4 multiplied by 3 is 12 Total = 30 The number 5 multiplied by 3 is 15 Total = 45 The number 6 multiplied by 3 is 18 Total = 63 The number 7 multiplied by 3 is 21 Total = 84 The number 8 multiplied by 3 is 24 Total = 108 The number 9 multiplied by 3 is 27 Total = 135 The number 10 multiplied by 3 is 30 Total = 165 • Output

  41. Cont’d… Give the output here • Global variables are static #include<iostream.h> #include<conio.h> int total =0; triple_it(int ); void main() { for(intctr=1;ctr<=10; ctr++) triple_it(ctr); getch(); } triple_it(int c) { intans; ans = c*3; total +=ans; cout<<"\n The number "<<c<<" multiplied by 3 is "<<ans; cout<<"\n Total = "<<total; return 0; }

  42. Functions with no types (void functions) • Functions with no return types are known as void functions • Does not return value to the caller function • Example #include<iostream.h> #include<conio.h> int sum(int); void print(int); void main() { int a=10; print(a); } void function int sum(int x) { int s=0; for(inti=1;i<=x;i++) s +=i; return s; } void print(int n) { cout<<"The sum is: "<<sum(n); }

  43. Arrays and Functions • When an array is admitted as parameter its type, identifier and pair of square brackets required • An array is passed as a reference (its address) not by value • Argument passing by value & reference is to be discussed later • Example: Write a function that receives an array and doubles each element of the array. void doubleArray(float arr[ ], int n); float myArray[] = {1.1, 3.3, 5.5, 7.7, 9.9}; doubleArray(myArray, size); Function Declaration/Prototype Function Call The size of the array Call to the function doubleArray() Aarray passing as an argument

  44. Passing arrays to a function… #include<iostream.h> #include<conio.h> void doubleArray(float arr[], int n) { for(inti=0; i<n; i++) arr[i] = 2*arr[i]; } void main() { float myArray[] = {1.1, 3.3, 5.5, 7.7, 9.9}; int size =sizeof(myArray)/sizeof(float); doubleArray(myArray, size); for(inti=0;i<size;i++) cout<<myArray[i]<<'\t'; getch(); } Output 2.2 6.6 11 15.4 19.8

  45. Passing arrays to a function… • Exercise: • Write a function that takes an array and its size as arguments and returns the sum of elements of the array

  46. Passing arrays to a function… #include<iostream.h> #include<conio.h> int sum(int[], int); // prototype of the function void main() { int a[] = { 11,33, 55,77 }; int size = sizeof(a)/sizeof(int); cout<<"sum(a,size) = " << sum(a,size) << endl; getch(); } int sum(int a[],int n) { int result=0; for (inti=0; i<n; i++) result += a[i]; return result; }

  47. Cont’d… • Exercise • Write a function that reverses elements of a given array • Write a function which finds a specific element in a given array and returns the index of the element if it is found • Write a function which finds the maximum element from a given array and returns the index of the element if it is found • Write a function which finds the minimum element from a given array and returns the index of the element if it is found

  48. Argument Passing by Value and by Reference

  49. Passing by Value (by Copy) • The two wordings “passing by value” and “passing by copy” mean the same thing in computer terms • When an argument (local variable) is passed by value, a copy of the variable’s value is sent to—and is assigned to—the receiving function’s parameter • If an expression is used in a function call to pass as a parameter, first the expression is evaluated and the value is passed to the local variable • The default method for passing parameters is by value, as just described, unless you pass arrays. • Arrays are always passed by the other method, by address to be discussed later

  50. Pass by Value/Copy 4 Main Main Cube(x) Cube(x) #include<iostream.h> #include<conio.h> int cube(int x) { x = x*x*x; return x; } void main () { int a = 4; cout<<cube(a)<<endl; cout<<cube(2*a-3)<<endl; cout<<“a = “<<a<<endl; getch(); } Cube(a) Cube(a) x=4*4*4 x=5*5*5 4 5 2*4-3=5 Output 64 125 a = 4

More Related