Eastern Mediterranean University Schl f Cmputing and Technlgy Infrmatin Technlgy Lecture2 Functins User Defined Functins Why d we need functins? T make yur prgram readable and rganized T reduce repeated cde Define a functins nce and re use everywhere yu want. This will save yu frm sme time. In ther wrds, a C prgram can be mdularized via the sensible use f prgrammer-defined functins. In general, mdular prgrams are far easier t write and debug than mnlithic prgrams. C als allws prgrammers t define their wn functins. The use f prgrammer-defined functins permits a large prgram t be brken dwn int a number f smaller, self-cntained units. Functins: A functin is a self-cntained prgram segment that carries ut sme specific, well-defined task. Every C prgram cnsists f ne r mre functins. One f these functins must be called main. Executin f the prgram always begins by carrying ut the instructins cntained in main. The same functin can be accessed frm several different places within a prgram. Once the functin has carried ut its intended actin, cntrl is returned t the pint frm which the functin was accessed. Functin prcesses infrmatin passed t it frm the calling prtin f the prgram, and returns a single value. This is the same definitin f functins in mathematics. (fr each x in X there exist y in Y such that f(x)= y ). A functin in C language is a blck f cde that perfrms a specific task. It has a name and it is reusable i.e. it can be executed frm as many different parts in a C prgram as required. It als, ptinally, returns a value t the calling prgram. Sme functins, hwever, accept infrmatin but d nt return anything. 1
S functin in a C prgram has sme prperties as discussed belw. Every functin has a unique name. This name is used: t be called frm main () functin. A functin can be called frm within anther functin. (Functin can call anther functin, r even can call itself (recursive). Remember that a C prgram must has at least ne functin called main (). A functin is independent and it can perfrm its task withut interventin frm r interfering with ther parts f the prgram. A functin perfrms a specific task. A task is a distinct jb that yur prgram must perfrm as a part f its verall peratin, such as adding tw r mre integer, srting an array int numerical rder, r calculating a cube rt etc. A functin returns a value t the calling prgram. This is ptinal and depends upn the task yur functin is ging t accmplish. Suppse yu want t just shw few lines thrugh functin, then it is nt necessary t return a value (as an example: a functin which prints string f characters nly as a heading). But if yu are calculating area f rectangle as an example, and wanted t use result smewhere in prgram, then yu have t send back (return) value t the calling functin. Nte that: Yu cannt imagine a C prgram withut functin. Structure f a Functin A general frm f a C functin lks like this: <return type> FunctinName (Argument1, Argument2, Argument3 ) Statement1; Statement2; Statement3; return value; return (value); r may be withut return statement (sme times) 2
User defined functins can be categrized as: Functin with n arguments and n return value Functin with n arguments and a return value Functin with arguments and n return value Functin with arguments and a return value When d we need functin prttype? Mst C prgrammers prefer t place the main() functin at the beginning f their prgrams. After all, main() is always the first part f a prgram t be executed. I recmmend yu t use this methd ( First place main functin then fllw all the functins after the main, and yu shuld apply the requirement as defined belw In such situatins, functin calls [within main()] are bund t precede the crrespnding functin definitins: frtunately, hwever, cmpilatin errrs can be avided by using a cnstruct knwn as a functin prttype. Functin prttypes are cnventinally placed at the beginning f a prgram (i.e., befre the main() functin) and are used t infrm the cmpiler f the name, data type, and number and data types f the arguments, f all userdefined functins emplyed in the prgram. The general frm f a functin prttype is data-type name(type 1, type 2,..., type n); ntice that semicln (;) must be cded as shwn abve in functin prttype where data-type represents the data type f the item returned by the referenced functin, name is the name f the functin, and type 1, type 2,..., type n are the data types f the arguments f the functin. Als, nte that it is nt necessary t specify the names f the arguments in a functin prttype. As an example: the functin prttype statement fr factrial functin can be written as: duble factrial ( int ); instead f duble factrial( int n); 3
Functins with n type. The use f vid What if we want t return n value? Imagine that we want t make a functin just t shw a message n the screen. We d nt need it t return any value. In this case we shuld use the vid type specifier fr the functin. This is a special specifier that indicates absence f type. vid printmessage;//func. prttype vid main () printmessage (); vid printmessage () printf("i'm a functin!"); The Arguments Argument1, Argument2, Argument3 are declared as: Type1 argument1, Type2 argument 2, Type 3 argument 3,..an s n. Example: int a, flat b, char d, int e; and s n. Ntice that cmma (,) must used t separate arguments and nt semicln (;). Functin Call: A functin can be accessed, r called, by specifying its name, fllwed by a list f arguments enclsed in parentheses and separated by cmmas. Nte that when yu call functin frm main then yu shuld nt include the type f the arguments. This mean that if yur functin declaratin is as fllws: int myfuncin(int A, flat B) then the call statement in main as fllws (as an example): 4
C= myfuncin(a,b); r as fllws: printf(" the value f C = %.3f\n", myfuncin(a,b)); If the functin call (call statement in main) des nt require any arguments then an empty pair f parentheses must fllw the name f the functin, as an example: func1 ( ). fr passing the value f an argument t a functin is called passing by value Example: int sum (int x, int y) int result; /* result is lcal variable */ result = x + y; return (result); /* r like: return result; */ In the abve: the returned value (result) is f type int, argument x is f type int, and argument y is f type int. Nte that: x and y are integer arguments t functin frm main ( r frm ther Functins). Als, the argument r variable (result) is called lcal variable. This mean that this variable is nly knwn with the functin (sum) defined abve. If main functin r any ther functin called by main has als anther variable with same name as result as an example, then they are ttally different and might have different values. vid main ( ) int x,y,v1; x=40;y=70; v1=sum(x,y); int sum(int k,int d) int R; R=k+d; return R; Value f R will be returned t main ( ) 5
Nte that the identifiers used t reference the arguments f a functin are lcal, in the sense that they are nt recgnized utside f the functin. Return statement: the bdy f the functins must include ne r mre return statements in rder t return a value t the calling prtin f the prgram. If the type f the functin is vid then functin has n return statement. A return statement causes the prgram lgic t return t the pint in the prgram frm which the functin was accessed. The general frm f a return statement is: return expressin; This statement causes the value f expressin t be returned t the calling part f the prgram. Of curse, the data type f expressin shuld match the declared data type f the functin. Fr a vid functin, which des nt return any value, the apprpriate return statement is simply: return; r even, dn t write the statement: return. A maximum f ne expressin can be included in a return statement. Thus, a functin can return a maximum f ne value t the calling part f the prgram. Hwever, a functin definitin can include multiple return statements, each cntaining a different expressin, which is cnditinally executed, depending n the prgram lgic. Example: int additin (int a, int b) int r; r=a+b; return (r); int main () int z; z = additin (5,3); printf("the result is %d \n",z); return 0; 6
1. Example prgram fr withut arguments & withut return value: In this prgram, n values are passed t the functin test and n values are returned frm this functin t main functin. vid test(); vid main() test(); vid test() int a = 50, b = 80; printf("\nvalues : \na = %d and b = %d\n\n", a, b); Output: values : a = 50 and b = 80 2. Example prgram fr withut arguments & with return value: In this prgram, n arguments are passed t the functin sum. But, values are returned frm this functin t main functin. Values f the variable a and b are summed up in the functin sum and the sum f these value is returned t the main functin. int sum(); vid main() int additin; additin = sum(); printf("\nsum f tw given values = %d\n\n", additin); int sum() int a = 50, b = 80; return a+b; Output: Sum f tw given values = 130 7
3. Example prgram fr with arguments & with return value: The value f m is passed as argument t the functin square. This value is multiplied by itself in this functin and multiplied value p is returned t main functin frm functin square. flat square ( flat x ); vid main( ) flat m ; printf ( "\nenter sme number fr finding square : "); scanf ( "%f", &m ) ; printf ( "\nsquare f the given number %.2f is %.2f\n\n",m,square(m) ); flat square ( flat x ) return x*x ; Output: Enter sme number fr finding square : 2 Square f the given number 2.00 is 4.00 4. Call by value: In call by value methd, the value f the variable is passed t the functin as parameter. The value f the actual parameter can nt be mdified by frmal parameter. Different Memry is allcated fr bth actual and frmal parameters. Because, value f actual parameter is cpied t frmal parameter. Nte: Actual parameter This is the argument which is used in functin call. Frmal parameter This is the argument which is used in functin definitin Example prgram fr C functin (using call by value): In this prgram, the values f the variables m and n are passed t the functin swap. These values are cpied t frmal parameters a and b in swap functin and used. vid swap(int a, int b); vid main() int m = 22, n = 44; printf("\nvalues befre swap m = %d nand n = %d\n", m, n); swap(m, n); vid swap(int a, int b) int tmp; tmp = a; 8
Output: a = b; b = tmp; printf("\nvalues after swap m = %d and n = %d\n\n", a, b); values befre swap m = 22 and n = 44 values after swap m = 44 and n = 22 5. Call by reference: In call by reference methd, the address f the variable is passed t the functin as parameter. The value f the actual parameter can be mdified by frmal parameter. Same memry is used fr bth actual and frmal parameters since nly address is used by bth parameters. Example prgram fr C functin (using call by reference): In this prgram, the address f the variables m and n are passed t the functin swap. These values are nt cpied t frmal parameters a and b in swap functin. Because, they are just hlding the address f thse variables. This address is used t access and change the values f the variables. vid swap(int &a, int &b); vid main() int m = 22, n = 44; printf("\nvalues befre swap m = %d and n = %d\n",m,n); swap(m, n); printf("\nvalues after swap a = %d nand b = %d\n\n",m,n); vid swap(int &a, int &b) int tmp; tmp = a; a = b; b = tmp; Output: values befre swap m = 22 and n = 44 values after swap a = 44 and b = 22 9
Randm Functin Generate randm number. It returns an integer value in the range between 0 and RAND_MAX Syntax: rand()% ttal number in the range + first number Ex: a in the range 12 t 25 a = rand() % (25-12+1) + 12 v1 = rand() % 100; // v1 in the range 0 t 99 v2 = rand() % 100 + 1; // v2 in the range 1 t 100 v3 = rand() % 30 + 1985; // v3 in the range 1985-2014 10