Download presentation
Presentation is loading. Please wait.
Published byDenis White Modified over 9 years ago
1
GE 211 Function in C++ Dr. Ahmed Telba
2
2 3.3Math 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 }Example cout << sqrt( 900.0 ); – sqrt (square root) function The preceding statement would print 30 – All functions in math library return a double
3
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.
4
Functions That Use Parameters #include using namespace std; void printAhmed(int a) { cout<<"Ahmed "<<a<<endl; } int main () { printAhmed(999); return 0; }
5
Functions That Use Multiple Parameters #include 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; }
6
// function returning the max between two numbers #include 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; }
7
Function Arguments: Call TypeDescription Call by valueThis 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 pointerThis 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 referenceThis 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.
8
#include 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); }
9
#include 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
10 3.3Math Library Functions Function arguments can be – Constants sqrt( 4 ); – Variables sqrt( x ); – Expressions sqrt( sqrt( x ) ) ; sqrt( 3 - 6x );
11
11
12
12 3.4Functions 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
13 3.5Function 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
14 3.5Function 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
15 3.5Function 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
16
#include // random number generator #include using namespace std; int main() { for (int x=1;x<25;x++) { cout<<"The Random number is = "<<rand()<< endl ; } } ------- #include using namespace std; int main() { for (int x=1;x<25;x++) { cout<<"The Random number is = "<<rand()%6 << endl ; //generate 0 to 5 }
17
#include using namespace std; // print string word void print(); main() { print(); } void print() { cout<<"I am c++"; }
18
#include 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 ; }
19
#include 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 ; }
20
// function overloading #include 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; }
21
#include using namespace std; float max(int x, float y) { if(x > y) return x; return y; } main() { cout<<max(5,5.4); }
22
#include using namespace std; int sum() { int x = 5, y = 4; return x + y; } main() { int z = sum(); cout<<z; return 0; }
23
#include // 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 ; }
24
#include // cubic of x=x^3 #include 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) ; }
25
#include // solving equation of x=x^n #include 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 ; }
26
#include //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";}
28
Random Number Generator #include 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; }
29
// compound assignment operators #include using namespace std; int main () { a =5 int a, b=3; a = b; a+=2; // equivalent to a=a+2 cout << a; return 0; }
30
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;
31
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
32
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).
33
Input output // i/o example #include 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; }
34
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;
35
// cin with strings #include 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; }
36
// stringstreams #include 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; }
37
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";
38
The while loop // custom countdown using while #include using namespace std; int main () { int n; cout "; cin >> n; while (n>0) { cout << n << ", ";..n; } cout << "FIRE!\n"; return 0; }
39
// countdown using a for loop #include using namespace std; int main () { for (int n=10; n>0; n..) { cout << n << ", "; } cout << "FIRE!\n"; return 0; }
41
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"; }
42
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 { }.
43
// function example #include 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; }
44
// void function example #include using namespace std; void printmessage () { cout << "I'm a function!"; } int main () { printmessage (); return 0; }
45
// passing parameters by reference #include 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; }
46
// more than one returning value #include 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; }
47
// default values in functions #include 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). */
48
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:
49
// overloaded function #include 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; }
50
Function
51
// factorial calculator #include 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; }
52
// declaring functions prototypes #include 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); }
53
#include main ( ) { cout << 7 << " is an integer.\n"; cout << 'a' << "is a character.\n"; }
54
#include using namespace std; main ( ) { cout<<10; cout<<20<<30; return 0; } cout<<10<< '\n'; cout<<20<<30<< '\n';
55
#include //#include using namespace std; // Program 1-4: Addition program //#include #include 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; }
56
cin >> integer1>>integer2 cout<<''sum= ''<<sum<<endl C=(f-32)*5/9;
57
#include main ( ) { int grade ; cout << " Enter the grade"; cin >>grade; if(grade>= 50) cout<<"pass" <<endl; else cout <<"fail"<<endl; return 0; }
58
if (gender==1) cout<<women <<endl; else cout <<man<<endl;
59
Formats in cpp:
60
#include 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; }
61
#include 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; }
62
Logic operations
63
#include 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; //Continued cout << “ Class average is: “ << average <<endl; return 0;
64
Counter
65
#include using namespace std; int main ( ) { for (int j=10; j<=100; j+=10) cout <<j<<endl; system("pause"); return 0; }
66
Function in c++ #include int square(int);//function prototype main() { for(int x=1;x<=10;x++) cout<<square(x)<<" "; cout<<endl; } //now function definition int square(int y) { return y*y; }
67
#include 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; }
68
// function example #include 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; }
69
Function in C++
70
function example #include 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; }
71
void function example #include using namespace std; void printmessage () { cout << "I'm a function!" << '\n‘; } int main () { printmessage (); return 0; }
72
// passing parameters by reference #include 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; }
73
// more than one returning value #include 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; }
74
// default values in functions #include 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; }
75
// overloaded function #include 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; }
76
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:
77
// factorial calculator #include 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; }
78
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:
79
// declaring functions prototypes #include 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"); }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.