# Functions

16. Dec 2017
1 von 25

### Functions

• 1. FUNCTIONS Definition: A function is a set of instructions that perform a specified task which repeatedly occurs in the main program. • A function is a self-contained program segment that carries out some specific, well- defined task. Every C program consists of one or more functions. One of these functions must be called main. • Execution of the program will always begin by carrying out the instructions in main. Additional functions will be subordinate to main, and perhaps to one another. • If a program contains multiple functions, their definitions may appear in any order, though they must be independent of one another. That is, one function definition cannot be embedded within another. • The same function can be accessed from several different places within a program. Once the function has carried out its planned action, control will be returned to the point from which the function was accessed. The general term of first line of functions can be written as: data-type function-name (formal argument 1, formal argument 2…formal argument n) • The formal arguments allow information to be transferred from the calling portion of the program to the function. They are also known as parameters or formal parameters. • These formal arguments are called actual parameters when they are used in function reference. • The names of actual parameters and formal parameters may be either same or different but their data type should be same. • All formal arguments must be declared after the definition of function. The remaining portion of the function definition is a compound statement that defines the action to be taken by the function. This compound statement is sometimes referred to as the body of the function. STRUCTURE OF A FUNCTION There are two main parts of the function. The function header and the function body. int sum(int x, int y) {
• 2. int ans = 0; //holds the answer that will be returned ans = x + y; //calculate the sum return ans; //return the answer } FUNCTION HEADER In the first line of the above code int sum(int x, int y) It has three main parts 1. The name of the function i.e. sum 2. The parameters of the function enclosed in paranthesis 3. Return value type i.e. int FUNCTION BODY What ever is written with in { } in the above example is the body of the function. TYPES OF FUNCTION: Functions are classified into two types as shown below a) PREDEFINED FUNCTONS( LIBRARY FUNCTIONS): C language provides number of function, that is used to carry out various commonly used operations or calculations called library function. C language provides library functions for the following tasks.  The library functions, that are used to carry out read/write operations  Functions that are used to carry out certain mathematical operations. Pre-Defined Functions FUNCTIONS User Defined Functions
• 3.  Functions that are used to perform operations on files.  Functions that are used to control C language etc.. Eg.Conversion of lower case to upper case #include<stdio.h> #include<conio.h> void main() { char txt[80]; int i,t; clrscr(); for(i=0;(txt[i]=getchar()!=’n’;++i); t=i; for(i=0;i<t;++i) putchar(toupper(txt[i])); } Output: Vrb publishers VRB PUBLISHERS b) USER-DEFINED FUNCTONS: These are written by the programmer to perform a particular task, that is repeatedly used in main program. These functions are helpful to break down a large program into smaller functions. NEED FOR USER-DEFINED FUNCTIONS: While it is possible to write any program using the main ( ) function and it leads to a number of problems, such as • The program becomes too large and complex. • The task of debugging, testing, and maintenance becomes difficult.
• 4. If a program is divided in two parts, then each part may be independently coded and later combined in to a single program. These sub-programs are called functions and much easier to understand, debug and test. ELEMENTS OF USER-DEFINED FUNCTIONS: To write an efficient user defined function, the programmer must familiar with the following three elements. a) Function definition b) Function call c) Function declaration. a) Function definition : It is the process of specifying and establishing the user defined function by specifying all of its elements and characteristics. b) Function call : A function can be called by typing the function name in a source program with parameters, if presence within parentheses. Eg: Function call without parameters. main() { message(); printf(“main message”); } message() { Printf(“Function messagen”); } Output: Function message main message
• 5. Eg: Function call with parameter main() { int z; z=add(3,9); printf(“Results..%d”,c); } int add(int a,int b) { int z; z=a+b; return(z); } Function declaration: The function can also be declared before they defined and invoked. Parameters: The data communication between the calling function and called function called parameter. There are two types of parameters are there, i) Actual parameter: These are the parameters transferred from the calling program to the called program. ii) Formal parameter; These are the parameters transferred into the calling function from the called program. Eg: main()
• 6. { ……. ……. fun1(a,b); ……. ……. } fun1(x,y) { ……… ……… } Where, a,b-actual parameters x,y-formal parameters The return statement: It may or may not be send back any values to the main program.if it does using the return statement. syntax : return; or return(expression); where,
• 7. return; does not return any value return(exp); returns the specified exp value to main program. Eg: if(a>0) return(1); else return(0); EXAMPLE Lowercase to Uppercase Character Conversion Using Function #include<stdio.h> #include<conio.h> char lower_to_upper(char c1) { char c2; c2= (c1>='a'&&c1<='z')?('A'+c1-'a'):c1; return (c2); } void main () { char lower, upper; clrscr(); printf("Enter a lower case character"); scanf("%c",&lower); upper=lower_to_upper(lower); printf("n The Upper case Equivalent is %cnn",upper);
• 8. getch(); } • This program consists of two functions-the required main function, preceded by the programmer-defined function lower-to-upper. Note that lower-to-upper carries out the actual character conversion. • This function converts only lowercase letters; all other characters are returned intact. A lowercase letter is transferred into the function via the argument c1, and the uppercase equivalent, c2, is returned to the calling portion of the program (i.e., to main) via the return statement.  Now consider the main function, which follows lower-to-upper. This function reads in a character (which may or may not be a lowercase letter) and assigns it to the char-type variable lower.  Function main then calls the function lower-to-upper, transferring the lowercase character (lower) to lower-to-upper, and receiving the equivalent uppercase character (upper) from lower-to-upper. The uppercase character is then displayed, and the program ends. Notice that the variables lower and upper in main correspond to the variables c l and c2 within lower-to-upper. ACCESSING A FUNCTION: • A function can be accessed (i.e., called) by specifying its name, followed by a list of arguments enclosed in parentheses and separated by commas. If the function call does not require any arguments, an empty pair of parentheses must follow the name of the function. • The function call may be a part of a simple expression (such as an assignment statement), or it may be one of the operands within a more complex expression. • The parameters in the body of the functions are called actual arguments as stated earlier, they may be expressed as constants, single variables or more complex expressions Example Calculating the biggest number: #include <stdio.h> main() { int a,b,c,d; printf(“n Enter value of a=”);
• 9. scanf(“%d”, &a); printf(“n Enter value of b=”); scanf(“%d”,&b); printf(“n Enter value of c=”); scanf(“%d”, &c); d=maxi(a,b); printf(“n maximum =%d”, maxi(c,d)); } maxi(x,y); int x,y { int z; z=(x>=y)? x:y; return z; } o The function maxi is accessed from two different places in main. In the first call actual arguments are a, b and in the second call c, d are the actual arguments. o A function declaration can be written as  datatype function name(); o It is the value of each actual argument that is transferred into the function and assigned to the corresponding formal argument. FUNCTION PROTOTYPES Definition: A function prototype is used for this purpose. Function prototypes are usually written at the beginning of a program, ahead of any programmer-defined functions (including main). The general form of a function prototype is data-type name( type 1 arg 1 , type 2 arg 2, . . ., type n arg n ) ;
• 10. • Where data- type represents the data type of the item that is returned by the function, name represents the function name, and type 1, type 2, . . . , type n represent the data types of the arguments arg1 , arg 2,. . . , arg n. • The functions are classified into the following types depending on whether the arguments are present or not and whether a value is returned or not. These also called as function prototypes. i) Function with no arguments and no return values ii) Function with arguments and no return values iii) Function with arguments and with return values iv) Function with no arguments and with return values i) Function with no arguments and no return values: Here in these functions there is no data transfer takes place between calling function and the called function. (i.e) The called program does not receive any data from the calling program and does not send back any value to calling program. Syntax: main() { …… …… fun1(); …… …… } fun1() { ……. ……. }
• 11. Example addition of two numbers: Main() { Void add(void); Add(); } Void add() { Int a,b,c; Printf(“Enter two numbers”); Scanf(“%d%d”,&a,&b); C=a+b; Printf(“Sum is…%d”,c); } Output: Enter two numbers:10 20 Sum is :30 ii) Function with arguments and no return values: The data are transferred from calling function to called function. (i.e)The called program receives some data from the calling program and does not send back any values to calling function. Syntax: Main() { …… …..
• 12. Fun1(a,b); …….. ……... } Fun1(x,y) { ……… ……… } Example addition of two numbers: main() { void add(int,int); int a,b,c; printf(“Enter two numbers”); scanf(“%d%d”,&a,&b); add(a,b); } void add(int x,int y) { int z; z=x+y; printf(“Sum is…%d”,c); } Output:
• 13. Enter two numbers:10 20 Sum is :30 iii) Function with arguments and with return value In this function the data is transferred between the calling function and called function. i.e., the called program receives some data from the calling program and send back a value return to the calling program ( two way data communication) Syntax: main ( ) data type fun1 ( x,y) { { ……… ……. ………. ……….. c = fun1 (a,b ); …….. ………. ……….. ………. return(z) ; } } Here, the continuous line indicates that, the data transfer takes place in between calling program and called program. Eg: Addition of two numbers: main ( ) { int add(int,int); int a,b,c; printf(“enter two numbers…”); scanf(“%d %d”,&a,&b); c = add(a,b );
• 14. printf(result is….%d”,c); } int add( int x,int y) { int z; z = x+y; return (z); } output: enter two numbers…..10 20 result is…..30 iv) Function with no arguments and with return value. In this function, there is one way data communicate takes palce,i.e., the calling program can not pass any arguments to the called program but, the called program may send some return value to the calling program. Syntax: main ( ) data type fun1 ( ) { { ……… ……. ………. ……….. c = fun1 ( ); …….. ………. ……….. ………. return(z) ; } } Eg: Addition of two numbers: main ( )
• 15. { int add( ); c = add( ); printf(result is….%d”,c); } int add( ) { int a,b,c; printf(“enter two numbers…”); scanf(“%d %d”,&a,&b); c = a+b; return (c); } output: enter two numbers…..10 20 result is…..30 PASSING ARGUMENTS TO A FUNCTION: • When a single value is passed to a function via an actual argument, the value of the actual argument is copied into the function. • Therefore, the value of the corresponding formal argument can be altered within the Function, but the value of the actual argument within the calling routine will not change. This procedure for passing the value of an argument to a function is known as passing by value. CALL BY VALUE AND CALL BY REFERENCE In c language there are two ways, that the parameter can be passes to a function, they are i) Call by value ii) Call by reference
• 16. Call by value: This method copies the values of actual parameter into the formal parameters of the function. here the changes of the formal parameters cannot affect the actual parameters. INTERCHANGING TWO VARIABLES USING CALL BY VALUE: #include<stdio.h> Void main() { int a,b; printf(“Enter the values of a and b”); scanf(“%d%d”,&a,&b); printf(“before swapping”); printf(“%d%d”,a,b); interchange(a,b); printf(“the value of a and b after swapping”); printf(“a=%d b=%d”,a,b); } void interchange(int x,int y) { int t; t=x; x=y; y=t; } INPUT: Enter the values of a and b
• 17. 100 200 Before swapping 100 200 OUTPUT: a=100 b=200; in the above program changes made in the formal parameter will not affect the actual parameter. Call by reference: Call by reference is another way of passing parameter to a function. here the address of arguments are copied into the parameter inside the function, the address is used to access the actual parameters as pointer type. INTERCHANGING TWO VARIABLES USING CALL BY REFERENCE: #include<stdio.h> Void main() { int a,b; printf(“Enter the values of a and b”); scanf(“%d%d”,&a,&b); printf(“before swapping”); printf(“%d%d”,a,b); interchange(&a,&b); printf(“the value of a and b after swapping”); printf(“a=%d b=%d”,a,b); } void interchange(int *x,int *y) {
• 18. int t; t=*x; *x=*y; *y=t; } INPUT: Enter the values of a and b 100 200 Before swapping 100 200 OUTPUT: a=200 b=100; in the above program changes made in the formal parameter will affect the actual parameter so the value of a and b are interchanged in the main program. SIMPLE FUNCTION PROGRAMS: 1) void main() { clrscr(); fun(); getch(); } Fun() { Char ch; Printf(“n Enter any alphabet”); Scanf(“%c”,&ch); If(ch>=65&&ch<=90) Return(ch); Else Return(ch+32); } 1) main()
• 19. { Float a,b; Printf(“Enter any value”); Scanf(“%f”,&a); B=square(a); Printf(“n square of %f if %f”,a,b); } Square(float x) { Float y; Y=x*x; Return(y); } 2) void main() { Message(); Printf(“cry and you stop the monotony”); } Message() { Printf(“smile and the world smiles with u”); } FUNCTION PROTOTYPE: 1) FUNCTION WITHOUT ARGUMENTS AND RETURN VALUE: void main() { int z; clrscr(); z=send(); printf(“you entered %d”,z); getch(); } int send() { int no; printf(“enter a number”); scanf(“%d”,&no); return(no); } 2) FUNCTION WITH ARGUMENTS AND NO RETURN VALUE:
• 20. void main() { clrscr(); printf(“enter the radius”); scanf(“%d”,&r); area(r); getch(); } area(int r) { s=2*pi*r; printf(“the area is %d”,s); } 3) FUNCTION WITH ARGUMENTS AND RETURN VALUE: int mult(int x,int y); int main() { int x,y; printf(“enter two numbers to be multiplied”); scanf(“%d%d”,&a,&b); printf(“product of matrix is”); a=mul(x,y); } int mul(int x,int y) { return x*y; } 4) FUNCTION WITH OUT ARGUMENTS AND NO RETURN VALUE: main() { cal sum(); } cal sum() { int x,y,z,d; printf(“enter the numbers”); scanf(“%d%d%d”,&x,&y,&z); d=x+y+z; printf(“the value of d is %d”,d); } PASSING ARGUMENTS TO FUNCTION:
• 21. call by value: void main() { clrscr(); add(10,15); add(55,64); add(168,325; getch(); } void add(int x,int y) [ int result; result=x+y; printf(“sum of %d and %d is%d”,x,y,result”);} RECURSION The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go in infinite loop. Recursive function are very useful to solve many mathematical problems like to calculate factorial of a number, generating Fibonacci series, Factorial using recursion: #include <stdio.h> int factorial(unsigned int i) { if(i <= 1) {
• 22. return 1; } return i * factorial(i - 1); } int main() { int i = 15; printf("Factorial of %d is %dn", i, factorial(i)); return 0; } Fibonacci series using recursion: #include <stdio.h> int fibonaci(int i) { if(i == 0) { return 0; } if(i == 1) { return 1; } return fibonaci(i-1) + fibonaci(i-2); } int main() { int i; for (i = 0; i < 10; i++) { printf("%dt%n", fibonaci(i)); } return 0; } Nesting Functions A function calling different functions inside, It is called as Nesting functions. #include <stdio.h> //Nesting of functions //calling function inside another function //calling fact inside print_fact_table function
• 23. void print_fact_table(int); int fact(int); void main(){ print_fact_table(5); } void print_fact_table(int n){ int i; for (i=1;i<=n;i++) printf("%d factorial is %dn",i,fact(i)); } int fact(int n){ if (n == 1) return 1; else return n * fact(n-1); } STORAGE CLASSES IN C A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program. These specifiers precede the type that they modify. There are the following storage classes, which can be used in a C Program auto register static extern The auto Storage Class The auto storage class is the default storage class for all local variables. { int m ount; auto int m onth; } The example above defines two variables with the same storage class, auto can only be used within functions, i.e., local variables. The register Storage Class The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location). { register int m iles; }
• 24. The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions. The static Storage Class The static storage class instructs the compiler to keep a local variable in existence during the lifetime of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared. In C programming, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class. #include <stdio.h> /* function declaration * / void func(void); static int count = 5; /* global variable * / m ain() { while(count--) { func(); } return 0; } /* function definition * / void func( void ) { static int i = 5; /* local static variable * / i++; printf("i is %d and count is %dn", i, count); } result: i is 6 and count is 4 i is 7 and count is 3 i is 8 and count is 2 i is 9 and count is 1 i is 10 and count is 0 The extern Storage Class The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. The extern modifier is most commonly used when there are two or more files sharing the same
• 25. global variables or functions as explained below. First File: main.c #include <stdio.h> int count ; extern void write_extern(); m ain() { count = 5; write_extern(); } Second File: support.c #include <stdio.h> extern int count; void write_extern(void) { printf("count is %dn", count); } 5