functions in c programming dr. ahmed telba. if else // if #include using namespace std; int main() {...

42
Functions in C Programming Dr. Ahmed Telba

Upload: arleen-james

Post on 03-Jan-2016

235 views

Category:

Documents


0 download

TRANSCRIPT

Functions in C Programming

Dr. Ahmed Telba

If else// if#include<iostream>using namespace std;int main(){unsigned short dnum ;cout<< "Enter number of day(1-7): ";cin>> dnum;cout<< "\n";if(dnum == 1)cout << "the day is Friday";else if(dnum == 2)cout << "the day is Saturday";else if(dnum == 3)cout << "the day is Sunday";else if(dnum == 4)cout << "the day is Monday";else if(dnum == 5)cout << "the day is Tuesday";else if(dnum == 6)cout << "the day is Tuesday";else if(dnum == 7)cout << "the day is Thursday";elsecout << "Sorry we're closed ";cout<<'\n';system("pause");return 0;}

Switch case ---// switch#include<iostream>using namespace std;int main(){ unsigned short dnum ;cout<< "Enter number of day(1-7): ";cin>> dnum;cout<< "\n";switch(dnum){case 1: // if dnum = 1cout << "the day is Friday";break;case 2: // if dnum = 2cout << "the day is Saturday";break;case 3: // if dnum = 3cout << "the day is Sunday";break;case 4: // if dnum = 4cout << "the day is Monday";break;case 5: // if dnum = 5cout << "the day is Tuesday";break;case 6: // if dnum = 6cout << "the day is Wednesday";break;case 7: // if dnum = 7cout << "the day is Thursday";break;default: // if dnum < 1 or dnum> 7cout << "Sorry we're closed ";break;}cout<< "\n";system("pause");return 0;}

Type of Variables• Global Variables

– Variables declared before main() function.– Global variables are defined to all parts in the program– If Global variable is changed in any part in the program,

this change appears in all the program• Local Variables

– Variables defined inside different functions, including main() function

– Local variables are defined only in their functions• Note: DO NOT use a local variable of the same name

as a global variable

Function

Example• #include <iostream.h>

int I; // I is a global variable

main()

{

int K;

/* K is a local varaible defined in the main */

}

Functions

Functions

Functions

Return and Input Types

Function Declarations

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 specified 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

specified 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 { }.

Example• #include <iostream.h> void print2number(int,int);

main(){

int x,y;x=3;y=4;print2number(x,y);

}

void print2number(int number1,int number2){

cout<<”number1,number2,number3;}

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; return 0;}

The result is 8

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.

Math Library Functions Revisited

• Introduction• Function Definition• Void function• Global Vs Local variables• Random Number Generator• Recursion• Function Overloading• Sample Code

C++ PROGRAMMING SKILLSPart 3

User-Defined Functions

Functions in C++• Experience has shown that the best way to develop and maintain large

programs is to construct it from smaller pieces(Modules)• This technique Called “Divide and Conquer”

main(){ ----- ----- ----- ----- . . . ---- ----- -----Return 0;}

Bad Development Approach

•Easer To

DesignBuildDebugExtendModifyUnderstandReuseBetter Organization

Wise Development Approach

main(){ ----- ----}

function f1(){ --- ---}

function f2(){ --- ---}

Functions in C++(Cont.)

• In FORTRAN Modules Known as Subprograms• In Pascal Modules known as Procedures & Functions• In C++ Modules Known as Functions & Classes• Programs use new and “prepackaged” modules

– New: programmer-defined functions and classes– Prepackaged: from the standard library

About Functions in C++• Functions invoked by a function–call-statement which consist of it’s

name and information it needs (arguments)• Boss To Worker Analogy A Boss (the calling/caller function) asks a worker (the called

function) to perform a task and return result when it is done.

Main

Boss

Function A Function B Function Z

WorkerWorker

Function B2Function B1

Worker

Worker Worker Note: usual main( ) Calls other functions, but other functions

can call each other

Function Calling

• Function Arguments can be:- Constant sqrt(9);- Variable sqrt(x);- Expression sqrt( x*9 + y) ;

sqrt( sqrt(x) ) ;

• Functions called by writingfunctionName (argument);orfunctionName(argument1, argument2, …);

• Examplecout << sqrt( 900.0 );

• sqrt (square root) function • The preceding statement would print 30• All functions in math library return a double

Function Calling

cout<< sqrt(9);

Function Name argument

3

Output

Parentheses used to enclose argument(s)

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

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

– After finished, passes back result

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

• 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

Function Definition

Function Definition• Syntax format for function definition

returned-value-type function-name (parameter-list){

Declarations of local variables 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)

Function Definition• 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

#include<iostream>using namespace std; // Creating and using a programmer-defined function. int square( int ); // function prototype int main() { // loop 10 times and calculate and output // square of x each time for ( int x = 1; x <= 10; x++ ) cout << square( x ) << " "; // function call cout << endl; system("pause"); return 0; // indicates successful termination } // end main

// square function definition returns square of an integer int square( int y ) // y is a copy of argument to function { return y * y; // returns square of y as an int } // end function square

#include<iostream>using namespace std;

int square(int); // prototypeint cube(int); // prototypemain(){ int i;

for (int i=1;i<=10;i++){

cout<< i<< "square=" << square(i) << endl;cout<< i<< "cube= " <<cube(i) << endl;

} // end forsystem("pause");return 0;

} // end main functionint square(int y) //function definition{

return y*y; // returned Result}

int cube(int y) //function definition{

return y*y*y; // returned Result}

#include<iostream>using namespace std; double maximum( double, double, double ); // function prototype int main() { double number1, number2; double number3; cout << "Enter three real numbers: "; cin >> number1 >> number2 >> number3; // number1, number2 and number3 are arguments to the maximum function call cout << "Maximum is: " << maximum( number1, number2, number3 ) << endl; system("pause"); return 0; } double maximum( double x, double y, double z ) { double max = x; // assume x is largest

if ( y > max ) // if y is larger, max = y; // assign y to max

if ( z > max ) // if z is larger, max = z; // assign z to max return max; // max is largest value } // end function maximum

Add two number• #include<iostream>• using namespace std;• void add2Nums(int,int);• main()• { int a, b;• cout<<"enter tow Number:";• cin >>a >> b;• add2Nums(a, b);• system("pause");•

• return 0;• }• void add2Nums(int x, int y)• {• cout<< x<< "+" << y << "=" << x+y;• }

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

#include <iostream>using namespace std;

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

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

x=2, y=6, z=14

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

Previous=99, Next=101

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

65

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

Please type a number: 9 9! = 362880

// 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);}

Type a number (0 to exit): 9Number is odd.Type a number (0 to exit): 6Number is even.Type a number (0 to exit): 1030Number is even.Type a number (0 to exit): 0Nu

Example

Including Functions

Including Functions

Variable Scope

Example: Bessel Function

Γ(n) = (n − 1)!

Example: Bessel Function• double J(int n,double xx)• {• double xasymp=17.5;• double tk,s;• int NN=60,k,i;• if(xx==0. && n==0) return 1.;• if(xx<xasymp)• {• tk=pow((xx/2.),n)/fact(n);• s=tk;• for(k=0;k<=NN;k++)• {• tk=-tk*xx*xx/4./(k+1.)/(k+n+1.);• s=s+tk;• }• }• else s=sqrt(2./Pi/xx)*cos(xx-Pi/4.-n*Pi/2.);• return(s);• }