Download presentation
Presentation is loading. Please wait.
Published byNathan Sutton Modified over 8 years ago
1
Functions Simple Functions Passing Arguments to Functions Returning Values from Functions Reference Arguments Overloaded Functions Recursion Inline Functions Default Arguments Scope and Storage Class Returning by Reference const Function Arguments
2
The Functions and its Benefits A function groups a number of program statements into a unit and gives it a name. This unit can then be invoked from other parts of the program leading to enhancing the conceptual organization of a program. Dividing a program into functions is one of the major principles of structured programming. Functions reduce program size (the reason they were invented, long ago). The function’s code is stored in only one place in memory, even though the function is executed many times in the course of the program. Functions in C++ (and C) are similar to subroutines and procedures in various other languages.
3
Benefits of Using Functions
4
Functions Declaration and Definition Each function has a name, a return data type, and an optional parameter list. Functions can declare local constants and variables. Except for the function main, you should prototype or declare the needed functions in advance before the starting point of the function main. The declaration tells the compiler that at some later point the function will be presented. The function declaration is terminated with a semicolon. Function declarations are also called prototypes, since they provide a model or blueprint for the function. The function signature: is the information in the declaration (the return data type, the name, the number and types of any arguments).
5
Functions Declaration Declaration of a function tells the compiler: “a function that looks like this is coming up later in the program, so it’s all right if you see references to it before you see the function itself.” Examples of functions declarations: void starline(); float netSalary(float, float); Names in the Declaration: In order to increase the clarity of function declarations use meaningful names for the function parameters, along with the data types. float netSalary(float salary, float tax);
6
Functions Declaration The general syntax for a function prototype is : returnType functionName ( parameterList ); Examples of functions declarations: double getSquare(double x); // one named parameter double Square(double); // one unnamed parameter int getMin(int nNum1, int nNum2); // two parameters int getSmall(int nNum1, int nNum2, int nNum3); // three parameters ….. int main() {………………..
7
// to compute the sum of even numbers among two integers #include int evenPrint(int j, int k); //function declaration int main() { int sum=0, x, y; cout<<"\n Enter two values :” <<endl; cin>>x>>y; sum=evenPrint(x,y);//function call cout<<"sum= "<<sum<<endl; return 0; } int evenPrint (int j, int k) //function definition { int i, sum=0; for(i=x;i<=y;i++) { if (i%2==0) cout << "\t" <<i; sum+=i; } } return sum; } A Simple Program Using Function Declaration
8
Eliminating the Function Declaration This approach is simpler for short programs, in that it removes the declaration, but it is less flexible. the programmer must give considerable thought to arranging the functions so that each one appears before it is called by any other. Sometimes this is impossible.
9
// to compute the sum of even numbers among two integers #include int evenPrint (int j, int k) //function definition { int i, sum=0; for(i=x;i<=y;i++) { if (i%2==0) cout << "\t" <<i; sum+=i; } } return sum; } int main() { int sum=0, x, y; cout<<"\n Enter two values to compute the sum of even numbers within them:“<<endl; cin>>x>>y; sum=evenPrint(x,y);//function call cout<<"sum= "<<sum<<endl; return 0; } A Simple Program with Eliminating the Function Declaration
10
The Function Definition
11
Rules About Defining Parameters of A Function Each parameter must have its own type. You cannot use the same type to declare multiple parameters (as you can when declaring variables). If a function has no parameters, the parentheses that come after the function's name contain nothing or the reserved word void. Examples : void starLinePrint(); void starLinePrint( void ); void LinePrint(char ch, int lineSize);
12
Arguments passing techniques The argument for a parameter is passed by copy ( by value), unless you insert the reference-of operator & after the parameter's type. When a parameter passes a copy of its argument, the function can alter only the copy of the argument used within the function itself. The original argument remains intact. By contrast, using the reference-of operator allows the argument to be passed by reference by declaring the parameter as a reference to its argument. In this case, the parameter becomes a special alias to its argument. Any changes the function makes to the parameter also affect the argument.
13
Call by value (copy parameters) Copy parameters take arguments that are constants, variables, or expressions. The type of argument must either match the type of the parameter or be compatible with it. You may use typecasting to tell the compiler how to adjust the type of the argument to match the type of the parameter. Reference parameters take arguments that are the names of variables. You cannot use an expression or a constant as an argument to a reference parameter since an expression does not have an address as a variable does.
14
Examples of functions definition double getSquare (double x) // one parameter { return x * x; } double Square (double& x) // one parameter, modifies its argument { x = x * x; return x; } int getMin (int Num1, int Num2) // two parameters { return (Num1 < Num2) ? Num1 : Num2; }
15
Examples of functions definition // Defining a function with three parameters: int getSmall (int nNum1, int nNum2, int nNum3) { if (nNum1 < nNum2 && nNum1 < nNum3) return nNum1; else if (nNum2 < nNum1 && nNum2 < nNum3) return nNum2; else return nNum3; }
16
// to compute the sum of even numbers among two integers #include int evenPrint (int j, int k) //function definition { int i, sum=0; for(i=j;i<=k;i++) { if (i%2==0) { cout << "\t" <<i; sum+=i; } } return sum; } int main() { char ch; int sum=0, x, y; do{ cout<<"\n Enter two values :“ <<endl; cin>>x>>y; sum=evenPrint(x,y);//function call cout<<"\n sum= "<<sum<<endl; cout<<"\n to continue press y "; cin>>ch; } while (ch == 'y‘ ); return 0; }
17
An Example for Arguments Passed by Value // demonstrates variable arguments passed by value #include void repchar(char, int); //function declaration int main() { char chin; int nin; cout << “Enter a character: “; cin >> chin; cout << “Enter number of times to repeat it: “; cin >> nin; repchar(chin, nin); return 0; } //-------------------------------------------------------------- void repchar(char ch, int n) //function declarator { for(int j=0; j<n; j++) //function body that repeatedly display a cout << ch;// character ch to n times cout << endl; }
18
An Example for Arguments Passed by Value
19
Call by Reference A reference provides an alias or a different name for the same variable. When arguments are passed by value, the called function creates a new variable of the same type as the argument and copies the argument’s value into it. An important advantage of passing by reference is that the function can access the actual variables in the calling program. Among other benefits, this provides a mechanism for passing more than one value from the function back to the calling program.
20
#include void swap(float* j, float* i) //function definition { float n; n=*j; *j=*i; *i=n; } int main() { float x, y; char ch; do { cout<<"\n Enter two values for x and y to be swapped : "<<endl; cin>>x>>y; swap(&x, &y);//function call cout<<"the values of x and y are : "<<x<<" and "<<y<<endl; cout<<"\n to continue press y "; cin>>ch; }while(ch=='y'); return 0; }
21
// demonstrates passing by reference #include using namespace std; int main() { void intfrac(float, float&, float&); //declaration float number, intpart, fracpart; //float variables do { cout << "\nEnter a real number: "; //number from user cin >> number; intfrac(number, intpart, fracpart); //find int and frac cout << "Integer part is " << intpart //print them << ", fraction part is " << fracpart << endl; } while( number != 0.0 ); //exit loop on 0.0 return 0; } // finds integer and fractional parts of real number void intfrac(float n, float& intp, float& fracp) { long temp = static_cast (n); //convert to long, intp = static_cast (temp); //back to float fracp = n - intp; //subtract integer part }
22
Structures as Arguments Entire structures can be passed as arguments to functions. // demonstrates passing structure as argument #include struct Distance { int feet; float inches; }; void engldisp( Distance ); //declaration int main() { Distance d1, d2; //define two lengths //get length d1 from user cout > d1.feet; cout > d1.inches; //get length d2 from user cout > d2.feet; cout > d2.inches; cout << “\nd1 = “; engldisp(d1); //display length 1 cout << “\nd2 = “; engldisp(d2); //display length 2 cout << endl; return 0; } void engldisp( Distance dd ) //parameter dd of type Distance { cout << dd.feet << “\’-” << dd.inches << “\””; }
23
#include struct Distance { int feet; float inches; }; Distance addengl(Distance, Distance); //declarations void engldisp(Distance); int main() { Distance d1, d2, d3; //define three lengths //get length d1 from user cout > d1.feet; cout > d1.inches; //get length d2 from user cout > d2.feet; cout > d2.inches; d3 = addengl(d1, d2); //d3 is sum of d1 and d2 cout << endl; engldisp(d1); cout << “ + “; engldisp(d2); cout << “ = “; engldisp(d3); cout << endl; return 0;} Distance addengl( Distance dd1, Distance dd2 ) // adds two structures of type Distance, returns sum { Distance dd3; //define a new structure for sum dd3.inches = dd1.inches + dd2.inches; //add the inches dd3.feet = 0; //(for possible carry) if(dd3.inches >= 12.0) //if inches >= 12.0, { dd3.inches -= 12.0; dd3.feet++; //increase feet } //by 1 dd3.feet += dd1.feet + dd2.feet; //add the feet return dd3; //return structure } //--------------------------------------------------------------// engldisp() void engldisp( Distance dd ) // display structure of type Distance in feet and inches { cout << dd.feet << “\’-” << dd.inches << “\””; }
24
Passing Structures by Reference // demonstrates passing structure by reference #include struct Distance //English distance { int feet; float inches; }; void scale( Distance&, float ); //function void engldisp( Distance ); //declarations int main() { Distance d1 = { 12, 6.5 }; //initialize d1 and d2 Distance d2 = { 10, 5.5 }; cout << “d1 = “; engldisp(d1); //display old d1 and d2 cout << “\nd2 = “; engldisp(d2); scale(d1, 0.5); //scale d1 and d2 scale(d2, 0.25); cout << “\nd1 = “; engldisp(d1); //display new d1 and d2 cout << “\nd2 = “; engldisp(d2); cout << endl; return 0; } //---------------------- scale() scales value of type Distance by factor void scale( Distance& dd, float factor) { float inches = (dd.feet*12 + dd.inches) * factor; dd.feet = static_cast (inches / 12); dd.inches = inches - dd.feet * 12; } //------------ display structure of type Distance in feet and inches void engldisp( Distance dd ) //parameter dd of type Distance { cout << dd.feet << “\’-” << dd.inches << “\””; }
25
Passing Arrays Using Pointers It’s more common to use pointer notation instead of array notation when arrays are passed to functions. #include using namespace std; const int MAX = 5; //number of array elements int main() { void centimize(double*); //prototype double varray[MAX] = { 10.0, 43.1, 95.9, 59.7, 87.3 }; centimize(varray); // pass array address for(int j=0; j<MAX; j++) //display new array values cout << “varray[“ << j << “]=” << varray[j] << “ centimeters” << endl; return 0; } //-------------------------------------------------------------- void centimize(double* ptrd) //change elements of varray to cm { for(int j=0; j<MAX; j++) *ptrd++ *= 2.54; //ptrd points to elements of varray }
26
Passing Arrays Using Pointers
27
Strings as Function Arguments Here’s an example that shows a string used as a function argument. // displays a string with pointer notation #include int main() { void dispstr(char*); //prototype char str[] = “Idle people have the least leisure.”; dispstr(str); //display the string return 0; } //-------------------------------------------------------------- void dispstr(char* ps) { while( *ps ) //until null character, cout << *ps++; //print characters cout << endl; }
28
Copying a String Using Pointers This example demonstrates a function that copies one string to another: // copies one string to another with pointers #include int main() { void copystr(char*, const char*); //prototype char* str1 = “Self-conquest is the greatest victory.”; char str2[80]; //empty string copystr(str2, str1); //copy str1 to str2 cout << str2 << endl; //display str2 return 0; } //-------------------------------------------------------------- void copystr(char* dest, const char* src) { while( *src ) //until null character, *dest++ = *src++; //copy chars from src to dest *dest = ‘\0’; //terminate dest }
29
Copying a String Using Pointers
30
Scope and Storage Class The scope of a variable determines which parts of the program can access it. The variable storage class determines how long it stays in existence. Two different kinds of scope are important here: local and file. –Variables with local scope are visible only within a block. –Variables with file scope are visible throughout a file. Note: A block is basically the code between an opening brace and a closing brace. Thus a function body is a block. There are two storage classes: automatic and static. –Variables with storage class automatic exist during the lifetime of the function in which they are defined. –Variables with storage class static exist for the lifetime of the program.
31
Local Variables Variables may be defined inside main() or inside other functions; the effect is the same, since main() is a function. local variables may defined within functions with storage class automatic or static. A local variable is not created until the function in which it is defined is called. #include int sum ( int x, int y); int main() { int a=2;//local variable with storage class automatic int b=3;//local variable cout<<"sum= "<<sum(a, b)<<endl; return 0; } int sum(int x, int y) { int z;//local variable z=x+y; return z; }
32
Static Local Variables A static local variable has the visibility of an automatic local variable. Its lifetime is the same as that of a global variable, except that it doesn’t come into existence until the first call to the function containing it. Thereafter it remains in existence for the life of the program. Static local variables are used when it’s necessary for a function to remember a value when it is not being executed; that is, between calls to the function. When static variables are initialized, the initialization takes place only once—the first time their function is called. They are not reinitialized on subsequent calls to the function, as ordinary local variables are.
33
#include float getavg(float); //declaration int main() {float data=1, avg; while( data != 0 ) { cout << “Enter a number: “; cin >> data; avg = getavg(data); cout << “New average is “ << avg << endl; } return 0; } float getavg(float newdata) // finds average of old plus new data { static float total = 0; //static variables are initialized static int count = 0; // only once per program count++; //increment count total += newdata; //add new data to total return total / count; //return the new average }
34
Global Variables global variables are defined outside of any function to be visible to all functions. it is visible to all those functions that follow the variable’s definition in the listing. Global variables are also sometimes called external variables, since they are defined external to any function. Global variables have storage class static, which means they exist for the life of the program. #include int a;//global variable int b=3;//global variable int sum(); int main() {a=2; cout<<"sum= "<<sum()<<endl; return 0; } int sum() {int z;//local variable z=a+b; return z; }
35
Overloaded Functions An overloaded function appears to perform different activities depending on the kind of data sent to it. It performs one operation on one kind of data BUT another different operation on a different kind of data. Overloading is like the joke about the famous scientist who insisted that the thermos bottle was the greatest invention of all time. Why? “It’s a miracle device,” he said. “It keeps hot things hot, but cold things it keeps cold. How does it know?”.
36
Overloading with Different Numbers of Arguments // demonstrates function overloading #include void repchar(); void repchar(char); void repchar(char, int); //declarations int main() {repchar(); repchar(‘=’); repchar(‘+’, 30); return 0; } void repchar() // displays 45 asterisks on one line {for(int j=0; j<45; j++) // always loops 45 times cout << ‘*’; // always prints asterisk cout << endl; } void repchar(char ch)// displays 45 copies of specified character on one line {for(int j=0; j<45; j++) // always loops 45 times cout << ch; // prints specified character cout << endl; } void repchar(char ch, int n)// displays specified number of a given character {for(int j=0; j<n; j++) // loops n times cout << ch; // prints specified character cout << endl; }
37
Overloading with Different Kinds of Arguments // demonstrates overloaded functions #include struct Distance {int feet; float inches; }; //English distance void engldisp( Distance ); //declarations void engldisp( float ); int main() {Distance d1; //distance of type Distance float d2; //distance of type float cout > d1.feet; //get length d1 from user cout > d1.inches; cout > d2;//get length d2 from user cout << “\nd1 = “; engldisp(d1); //display length 1 cout << “\nd2 = “; engldisp(d2); //display length 2 cout << endl; return 0; } void engldisp( Distance dd ) //parameter dd of type Distance { cout << dd.feet << “\’-” << dd.inches << “\””;} void engldisp( float dd ) //parameter dd of type float {int feet = static_cast (dd / 12); float inches = dd - feet*12; // display variable of type float in feet and inches cout << feet << “\’-” << inches << “\””; }
38
Recursion Recursion involves a function calling itself. Every recursive function must be provided with a way to end the recursion. //calculates factorials using recursion #include unsigned long factfunc(unsigned long); //declaration int main() { int n; //number entered by user unsigned long fact; //factorial cout << “Enter an integer: “; cin >> n; fact = factfunc(n); cout << “Factorial of “ << n << “ is “ << fact << endl; return 0; } unsigned long factfunc ( unsigned long n) // calls itself to calculate factorials {if(n > 1) return n * factfunc(n-1); //self call else return 1; }
39
Inline Functions
40
#include inline float lbstokg (float pounds) // converts pounds to kilograms { return 0.453592 * pounds; } int main() { float lbs; cout << “\n Enter your weight in pounds: “; cin >> lbs; cout << “Your weight in kilograms is “ << lbstokg(lbs) << endl; return 0; }
41
Notes
42
Math Library Functions Math library functions allow the programmer to perform certain common mathematical calculations. All functions in the math library return the data type double. To use the math library functions, include the header file.
43
MethodDescriptionExample ceil( x ) rounds x to the smallest integer not less than x ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 cos( x ) trigonometric cosine of x (x in radians) cos( 0.0 ) is 1.0 exp( x ) exponential function e x exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906 fabs( x ) absolute value of x fabs( 5.1 )= fabs( -5.1 )= 5.1 fabs( 0.0 ) is 0.0 floor( x ) rounds x to the largest integer not greater than x floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0 fmod( x, y ) remainder of x / y as a floating point number fmod( 13.657, 2.333 ) is 1.992 log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0 log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0 log10( 100.0 ) is 2.0 pow( x, y ) x raised to power y ( x y ) pow( 2, 7 ) is 128 pow( 9,.5 ) is 3 sin( x ) trigonometric sine of x (x in radians) sin( 0.0 ) is 0 sqrt( x ) square root of x sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0 tan( x ) trigonometric tangent of x (x in radians)tan( 0.0 ) is 0
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.