ge 211 function in c++ dr. ahmed telba. 2 3.3math library functions defining a function: the general...

79
GE 211 Function in C++ Dr. Ahmed Telba

Upload: denis-white

Post on 03-Jan-2016

234 views

Category:

Documents


1 download

TRANSCRIPT

GE 211Function in C++

Dr. Ahmed Telba

2

3.3 Math Library Functions• Defining a Function:• The general form of a C++ function definition

is as follows:• return_type function_name( parameter list )

{ body of the function }Examplecout << sqrt( 900.0 );

– sqrt (square root) function The preceding statement would print 30

– All functions in math library return a double

• A C++ function definition consists of a function header and a function body. Here are all the parts of a function:

• Return Type: A function may return a value. The return _type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.

• Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.

• Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

• Function Body: The function body contains a collection of statements that define what the function does.

Functions That Use Parameters• #include <iostream>• using namespace std;• • void printAhmed(int a)• {• cout<<"Ahmed "<<a<<endl;

• }

• int main ()• {

• printAhmed(999);• return 0;• }

Functions That Use Multiple Parameters• #include<iostream>• using namespace std;• int addnum (int x,int y)• {• int answer=x+y;

• return answer;

• }

• int main()• {

• cout<<"The Result is integer = "<<addnum (33,55)<< endl ;• return 0;• }

• // function returning the max between two numbers• #include <iostream>• using namespace std;• // function declaration• int max(int num1, int num2);• int main ()• { // local variable declaration:• int a = 100; int b = 200; int ret;• // calling a function to get max value.• ret = max(a, b);• cout << "Max value is : " << ret << endl;• return 0; }• // function returning the max between two numbers• int max(int num1, int num2) • {• // local variable declaration• int result; • if (num1 > num2)• result = num1;• else• result = num2; • return result; }

Function Arguments:Call Type Description

Call by value This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

Call by pointer This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

Call by reference This method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

• #include <iostream>• using namespace std;• int mult ( int x, int y );• int main()• {• int x;• int y;• cout<<"Please input two numbers to be multiplied: ";• cin>> x >> y;• cin.ignore();• cout<<"The product of your two numbers is "<< mult ( x, y ) <<"\n";• cin.get();• }• int mult ( int x, int y )• {• return x * y;• //return (9);• }

• #include <iostream>• using namespace std;• int sum(int a, int b=20)• {• int result;• result = a + b;• return (result);• }• int main ()• {• // local variable declaration:• int a = 100;• int b = 200;• int result;• // calling a function to add the values.• result = sum(a, b);• cout << "Total value is :" << result << endl;• // calling a function again as follows.• result = sum(a);• cout << "Total value is :" << result << endl;• • return 0;• }

10

3.3 Math Library Functions

• Function arguments can be– Constants• sqrt( 4 );

– Variables• sqrt( x );

– Expressions• sqrt( sqrt( x ) ) ;• sqrt( 3 - 6x );

11

Method Description Example 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 ex exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906

fabs( x ) absolute value of x fabs( 5.1 ) is 5.1 fabs( 0.0 ) is 0.0 fabs( -8.76 ) is 8.76

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 (xy) 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

Fig. 3.2 Math library functions.

12

3.4 Functions• Functions

– Modularize a program– Software reusability

• Call function multiple times • Local variables

– Known only in the function in which they are defined– All variables declared in function definitions are local variables

• Parameters– Local variables passed to function when called– Provide outside information

13

3.5 Function Definitions

• Function prototype– Tells compiler argument type and return type of function– int square( int );

• Function takes an int and returns an int– Explained in more detail later

• Calling/invoking a function– square(x);– Parentheses an operator used to call function

• Pass argument x• Function gets its own copy of arguments

– After finished, passes back result

14

3.5 Function Definitions• Format for function definition

return-value-type function-name( parameter-list ){ declarations and statements}

– Parameter list• Comma separated list of arguments

– Data type needed for each argument• If no arguments, use void or leave blank

– Return-value-type• Data type of result returned (use void if nothing returned)

15

3.5 Function Definitions• Example function

int square( int y )

{

return y * y;

}• return keyword

– Returns data, and control goes to function’s caller• If no data to return, use return;

– Function ends when reaches right brace• Control goes to caller

• Functions cannot be defined inside other functions• Next: program examples

• #include<iostream> // random number generator • #include<cstdlib> • using namespace std;• int main()• {• for (int x=1;x<25;x++)• {• cout<<"The Random number is = "<<rand()<< endl ;• } }• -------• #include<iostream>• #include<cstdlib>• using namespace std;• int main()• {• for (int x=1;x<25;x++)• {• cout<<"The Random number is = "<<rand()%6 << endl ; //generate 0 to 5 • }• }

• #include<iostream>• using namespace std;• // print string word • void print();• main()• {• print();

• }• void print()• {• cout<<"I am c++";• }

• #include <iostream>• using namespace std;• // add number from 1:50• int sum(int);• int main ()

• { • int x ;• cout<<" sumion is :- "<<sum (x) ;

• }• int sum (int a)• {• int su =0 ;• for(int i=1 ; i<=50 ;i++)• su+=i ;• return su ;• }

• #include<iostream>• using namespace std;• //vectorial of used number

• int mult(int);• main()• {• int n;• cin>>n;• cout<<mult(n);

• }• int mult(int x)• {int i,mult=1;• for(i=1;i<=x;i++)• mult=mult*i;• return mult ;• }

// function overloading • #include<iostream>• using namespace std;• void print(int x)• {• cout<<"The Result is integer = "<<x<< endl ;• }• void print(double x)• {• cout<<"The Result is double = "<<x<< endl ;• }• void print(char x)• {• cout<<"The Result is char = "<<x<< endl ;• }• int main( )• {• print(33.114);• print('k');• print(44);• return 0;• }

• #include<iostream>• using namespace std;• float max(int x , float y)• {• if(x > y)• return x;• return y;• }• main() {• cout<<max(5,5.4);• }

• #include<iostream>• using namespace std;

• int sum()• {• int x = 5 , y = 4;• return x + y;• }• main()• {• int z = sum();• cout<<z;• return 0;• }

• #include <iostream> // solve equation x^2+25• using namespace std;• int tow(int) ;• int main()• { • int x ;• cout<<"Enter the number x : "<<endl ;• cin>>x ;• cout<<"y=x*x +25 = "<<tow(x) <<endl ;

• }• int tow(int p)• {• int y ;• y= (p*p)+25 ;• return y ;• }

• #include <iostream>// cubic of x=x^3• #include <cmath>• using namespace std;• int sqrt (int) ;• int main ()• { • int x ;• cout<<"Enter x " ;• cin>>x ;• cout<<"The sqrt of "<<x <<" = "<<sqrt(x) ;

• }• //end main

• int sqrt (int a)• {• return (a*a*a) ;• }

• #include <iostream> // solving equation of x=x^n• #include <cmath>• using namespace std;• void maths( ) ;• int main ()• { • maths();

• }• void maths( )• {• int sum =0 ;• int x , n ;• cout<<"Enter base number : " ;• cin>>x ;• cout<<"Enter power number : " ;• cin>>n ;• for (int i=2 ; i<=n ; i+=2) {• sum=pow(x,i) ;• sum+=sum; • }• cout<<"The Resulit = "<<sum ;• }

• #include<iostream> //Odd & Even number • using namespace std;• main(){• for(int i=1;i<=100;i++)• if(i%2==0)• cout<<i<<" : Even ."<<"\n";• else• if(i%2==1)• cout<<i<<" : Odd ."<<" \t";}

Random Number Generator• #include <iostream>• #include <cstdlib>• using namespace std;• int main( )• {

• int i;• srand(99);• for (i = 0; i < 10; i++)• cout << (rand( ) % 11) << endl ;• srand(99);• for (i = 0; i < 10; i++)• cout << (rand( ) % 11) << endl ;• return 0;• }

// compound assignment operators #include <iostream> using namespace std; int main () { a =5 int a, b=3; a = b; a+=2; // equivalent to a=a+2 cout << a; return 0; }

Increase and decrease (++, --)

• Increase and decrease (++, --) • Shortening even more some expressions, the

increase operator (++) and the decrease operator (--) increase or reduce by one the value stored in a variable. They are equivalent to +=1 and to .=1, respectively. Thus:

• c++; === c+=1; === c=c+1;

Bitwise Operators ( &, |, ^, ~, <<, >> ) Bitwise operators modify variables considering the bit patterns that represent the values they store.

a = 5 + (7 % 2) // with a result of 6, or a = (5 + 7) % 2 // with a result of 0

Standard Output (cout) • By default, the standard output of a program

is the screen, and the C++ stream object defined to access it is cout.

• cout is used in conjunction with the insertion operator, which is written as << (two "less than" signs).

Input output • // i/o example • #include <iostream> using namespace std; int main () { int i; cout << "Please enter an integer value: "; cin >> i; cout << "The value you entered is " << i; cout << " and its double is " << i*2 << ".\n"; return 0; }

• You can also use cin to request more than one datum input from the user: • cin >> a >> b; • is equivalent to: • cin >> a; • cin >> b; • cin and strings • We can use cin to get strings with the extraction operator (>>) as we do with

fundamental data type variables: • cin >> mystring;

// cin with strings #include <iostream> #include <string> using namespace std; int main () { string mystr; cout << "What's your name? "; getline (cin, mystr); cout << "Hello " << mystr << ".\n"; cout << "What is your favorite team? "; getline (cin, mystr); cout << "I like " << mystr << " too!\n"; return 0; }

// stringstreams #include <iostream> #include <string> #include <sstream> using namespace std; int main () { string mystr; float price=0; int quantity=0; cout << "Enter price: "; getline (cin,mystr); stringstream(mystr) >> price; cout << "Enter quantity: "; getline (cin,mystr); stringstream(mystr) >> quantity; cout << "Total price: " << price*quantity << endl; return 0; }

if (x == 100) cout << "x is 100"; else cout << "x is not 100"; --if (x > 0) cout << "x is positive"; else if (x < 0) cout << "x is negative"; else cout << "x is 0";

The while loop // custom countdown using while #include <iostream> using namespace std; int main () { int n; cout << "Enter the starting number > "; cin >> n; while (n>0) { cout << n << ", "; ..n; } cout << "FIRE!\n"; return 0; }

// countdown using a for loop #include <iostream> using namespace std; int main () { for (int n=10; n>0; n..) { cout << n << ", "; } cout << "FIRE!\n"; return 0; }

switch (x) { case 1: case 2: case 3: cout << "x is 1, 2 or 3"; break; default: cout << "x is not 1, 2 nor 3"; }

Functions (I) Using functions we can structure our programs in a more modular way, accessing all the potential

that structured programming can offer to us in C++. A function is a group of statements that is executed when it is called from some point of the

program. The following is its format: type name ( parameter1, parameter2, ...) { statements } where: • type is the data type specifier of the data returned by the function. • name is the identifier by which it will be possible to call the function. • parameters (as many as needed): Each parameter consists of a data type specifier followed by

an identifier, like any regular variable declaration (for example: int x) and which acts within the

function as a regular local variable. They allow to pass arguments to the function when it is called. The

different parameters are separated by commas. • statements is the function's body. It is a block of statements surrounded by braces { }.

// function example

#include <iostream> using namespace std; int subtraction (int a, int b) { int r; r=a - b; return (r); } int main () { int x=5, y=3, z; z = subtraction (7,2); cout << "The first result is " << z << '\n'; cout << "The second result is " << subtraction (7,2) << '\n'; cout << "The third result is " << subtraction (x,y) << '\n'; z= 4 + subtraction (x,y); cout << "The fourth result is " << z << '\n'; return 0; }

// void function example #include <iostream> using namespace std; void printmessage () { cout << "I'm a function!"; } int main () { printmessage (); return 0; }

// passing parameters by reference #include <iostream> using namespace std; void duplicate (int& a, int& b, int& c) { a*=2; b*=2; c*=2; } int main () { int x=1, y=3, z=7; duplicate (x, y, z); cout << "x=" << x << ", y=" << y << ", z=" << z; return 0; }

// more than one returning value #include <iostream> using namespace std; void prevnext (int x, int& prev, int& next) { prev = x-1; next = x+1; } int main () { int x=100, y, z; prevnext (x, y, z); cout << "Previous=" << y << ", Next=" << z; return 0; }

// default values in functions #include <iostream> using namespace std; int divide (int a, int b=2) { int r; r=a/b; return (r); } int main () { cout << divide (12); cout << endl; cout << divide (20,4); return 0; } // /*we have only specified one argument, but the function divide allows up to two. So the function

divide has assumed that the second parameter is 2 since that is what we have specified to happen if this

parameter was not passed (notice the function declaration, which finishes with int b=2, not just int b). Therefore the result

of this function call is 6 (12/2). */

• Overloaded functions. • In C++ two different functions can have the

same name if their parameter types or number are different. That

• means that you can give the same name to more than one function if they have either a different number of

• parameters or different types in their parameters. For example:

// overloaded function #include <iostream> using namespace std; int operate (int a, int b) { return (a*b); } float operate (float a, float b) { return (a/b); } int main () { int x=5,y=2; float n=5.0,m=2.0; cout << operate (x,y); cout << "\n"; cout << operate (n,m); cout << "\n"; return 0; }

Function

// factorial calculator #include <iostream> using namespace std; long factorial (long a) { if (a > 1) return (a * factorial (a-1)); else return (1); } int main () { long number; cout << "Please type a number: "; cin >> number; cout << number << "! = " << factorial (number); return 0; }

// declaring functions prototypes #include <iostream> using namespace std; void odd (int a); void even (int a); int main () { int i; do { cout << "Type a number (0 to exit): "; cin >> i; odd (i); } while (i!=0); return 0; } void odd (int a) { if ((a%2)!=0) cout << "Number is odd.\n"; else even (a); } void even (int a) { if ((a%2)==0) cout << "Number is even.\n"; else odd (a); }

#include <iostream.h>main ( ) {

cout << 7 << " is an integer.\n";cout << 'a' << "is a character.\n";

}

#include<iostream>using namespace std;main ( ){ cout<<10; cout<<20<<30; return 0;}• cout<<10<< '\n'; • cout<<20<<30<< '\n';

#include <iostream>//#include <conio>using namespace std;

// Program 1-4: Addition program//#include<iostream.h>#include<conio.h>main ( ) {

int integer1, integer2, sum;cout <<"Enter first integer\n";cin >> integer1;cout <<"Enter second integer\n";cin >> integer2;sum= integer1+integer2;cout <<"sum="<<sum<<endl;getch();

return 0; }

• cin >> integer1>>integer2• cout<<''sum= ''<<sum<<endl• C=(f-32)*5/9;

#include <iostream.h>main ( ){int grade ;cout << " Enter the grade";cin >>grade;if(grade>= 50)cout<<"pass" <<endl;elsecout <<"fail"<<endl;return 0; }

• if (gender==1)• cout<<women <<endl;• else• cout <<man<<endl;

Formats in cpp:

#include<iostream.h>main ( ){int n;cin >> n;cout<< “ n after adding 2 = “ << a+= 2 <<endl;cout<< “ n after a subtracting 2 = “ << a-= 2 <<endl;cout<< “ n after dividing by 2 = “ << a/= 2 <<endl;cout<< “ n after multiplying by 2 = “ << a*= 2 <<endl;cout<< “ n mod 2 = “ << a %= 2 <<endl;return 0;}

#include<iostream.h>main ( ){int c;c = 5;cout << c << endl;cout << c++ <<endl;cout << c <<endl;c=5;cout << c << endl << endl;cout << ++c << endl;cout << c << endl;system("pause");return 0;}

Logic operations

#include<iostream.h>main ( ){int counter, grade, total ,average;total = 0;counter = 1;//while (counter <= 10)while (counter <= 0) {cout<< “ Enter grade : “;cin >>grade;total = total + grade;counter = counter + 1;}cout<<endl;average = total /10;//Continuedcout << “ Class average is: “ << average <<endl;return 0; 

• Counter

#include<iostream>using namespace std;int main ( ){

for (int j=10; j<=100; j+=10)cout <<j<<endl;system("pause");return 0;}

Function in c++#include<iostream.h>int square(int);//function prototypemain(){

for(int x=1;x<=10;x++) cout<<square(x)<<" "; cout<<endl;}//now function definitionint square(int y){

return y*y;}

• #include <iostream>• using namespace std;• • int main ()• {• // local variable declaration:• int a = 100;• • // check the boolean condition• if( a < 20 )• {• // if condition is true then print the following• cout << "a is less than 20;" << endl;• }• else• {• // if condition is false then print the following• cout << "a is not less than 20;" << endl;• }• cout << "value of a is : " << a << endl;• • return 0;• }

// function example#include <iostream>using namespace std;

int addition (int a, int b){ int r; r=a+b; return (r);}

int main (){ int z; z = addition (5,3); cout << "The result is " << z <<endl; ; return 0;}

Function in C++

function example#include <iostream>using namespace std;

int subtraction (int a, int b){ int r; r=a-b; return (r);}

int main (){ int x=5, y=3, z; z = subtraction (7,2); cout << "The first result is " << z << '\n'; cout << "The second result is " << subtraction (7,2) << '\n'; cout << "The third result is " << subtraction (x,y) << '\n'; z= 4 + subtraction (x,y); cout << "The fourth result is " << z << '\n'; return 0;}

void function example#include <iostream>using namespace std;

void printmessage (){ cout << "I'm a function!" << '\n‘;}

int main (){ printmessage (); return 0;}

// passing parameters by reference#include <iostream>using namespace std;

void duplicate (int& a, int& b, int& c){ a*=2; b*=2; c*=2;}

int main (){ int x=1, y=3, z=7; duplicate (x, y, z); cout << "x=" << x << ", y=" << y << ", z=" << z; return 0;}

// more than one returning value#include <iostream>using namespace std;

void prevnext (int x, int& prev, int& next){ prev = x-1; next = x+1;}

int main (){ int x=100, y, z; prevnext (x, y, z); cout << "Previous=" << y << ", Next=" << z; return 0;}

// default values in functions

#include <iostream>using namespace std;

int divide (int a, int b=2){ int r; r=a/b; return (r);}

int main (){ cout << divide (12); cout << endl; cout << divide (20,4); return 0;}

// overloaded function#include <iostream>using namespace std;

int operate (int a, int b){ return (a*b);}

float operate (float a, float b){ return (a/b);}

int main (){ int x=5,y=2; float n=5.0,m=2.0; cout << operate (x,y); cout << "\n"; cout << operate (n,m); cout << "\n"; return 0;}

• Recursivity.• Recursivity is the property that functions have to be

called by themselves. It is useful for many tasks, like sorting or calculate the factorial of numbers. For example, to obtain the factorial of a number (n!) the mathematical formula would be:

n! = n * (n-1) * (n-2) * (n-3) ... * 1 more concretely, 5! (factorial of 5) would be:

5! = 5 * 4 * 3 * 2 * 1 = 120 and a recursive function to calculate this in C++ could be:

// factorial calculator#include <iostream>using namespace std;

long factorial (long a){ if (a > 1) return (a * factorial (a-1)); else return (1);}

int main (){ long number; cout << "Please type a number: "; cin >> number; cout << number << "! = " << factorial (number); return 0;}

Declaring functions• Until now, we have defined all of the functions before the first appearance of calls to them in the

source code. These calls were generally in function main which we have always left at the end of the source code. If you try to repeat some of the examples of functions described so far, but placing the function main before any of the other functions that were called from within it, you will most likely obtain compiling errors. The reason is that to be able to call a function it must have been declared in some earlier point of the code, like we have done in all our examples.

But there is an alternative way to avoid writing the whole code of a function before it can be used in main or in some other function. This can be achieved by declaring just a prototype of the function before it is used, instead of the entire definition. This declaration is shorter than the entire definition, but significant enough for the compiler to determine its return type and the types of its parameters.

Its form is:

type name ( argument_type1, argument_type2, ...);

It is identical to a function definition, except that it does not include the body of the function itself (i.e., the function statements that in normal definitions are enclosed in braces { }) and instead of that we end the prototype declaration with a mandatory semicolon (;).

The parameter enumeration does not need to include the identifiers, but only the type specifiers. The inclusion of a name for each parameter as in the function definition is optional in the prototype declaration. For example, we can declare a function called protofunction with two int parameters with any of the following declarations:

// declaring functions prototypes#include <iostream>using namespace std;void odd (int a);void even (int a);int main (){ int i; do { cout << "Type a number (0 to exit): "; cin >> i; odd (i); } while (i!=0); return 0;}void odd (int a){ if ((a%2)!=0) cout << "Number is odd.\n"; else even (a);}void even (int a){ if ((a%2)==0) cout << "Number is even.\n";else odd (a); system("pause");}