Sie sind auf Seite 1von 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

USER-DEFINED FUNCTIONS
INTRODUCTION
One of the strength of C functions are easy to define and use. C functions can be classified into two categories, namely, Library ( Not required to be written by us ) and User-Defined (developed by the user at the time of writing a program) functions. main is an example of user-defined functions. printf and scanf belong to the category of library functions. However, a user-defined function can later become a part of the C program library. In fact, this is one of the strength of C language.

Need for User-Defined Functions:


main is a specially recognized function in C. Every program must have a main function to indicate where the program has to begin its execution. While it is possible to code any program utilizing only main function, it leads to a number of problems. The program may become too large and complex and as a result the task of debugging, testing and maintaining becomes difficult. If a program is divided into functional parts, then each part may be independently coded and later combined into a single unit. subprograms called FUNCTIONS are much easier to understand, debug and test. There are times when certain type of operations or calculations is repeated at many points throughout a program. We may repeat the program statements whenever they are needed. It is another approach to design a program that can be called and used whenever required. This saves both time and space. The various advantages of functions are: Reusability and Reduction of code size: The existing functions can be re-used as building blocks to create new programs which results in reduced program size. The functions can be used any number of times. Readability of the program can be increased: One can keep track of what each function is doing. Modular Programming approach: Large program is divided into small sub programs, each performs individual/specific task which makes the program development more manageable. Easier to Debug: Locating and isolating the errors are becomes much easier. Built Library: Repeatedly used functions can be generalized, tested and kept in a library for future use. It reduces program development time and coding time. Functions Sharing: Functions can be shared by many programs / Programmers.
Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 1 of 27

These

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

The division approach clearly results in a number of advantages. 1. It facilitates top-down modular programming style. In this, the high-level logic of the overall problem is solved first. While the details of each lower-level functions are addressed later. 2. The length of a source program can be reduced by using functions at appropriate places. 3. It is easy to locate and isolate a faulty function for further investigations. 4. A function may be used by many other programs. This means that a C programmer can build on what have others have already done, instead of starting allover again from scratch. MAIN PROGRAM

Function A

Function B

Function C

B1

B2

Figure: Top-down modular programming using functions

A Multi-Functions Program:
A function is a self-contained block of code that performs a particular task. Once a function has been designed and packed, it can be treated as a black box that takes some data from the main program and returns a value. Every C program can be designed by using a collection of these black-boxes known as functions.
void printline (void); /* Declaration */ main() { printline(); printf(This illustrates the use of C functions); printline(); } void printline(void) { int i; for(i=1 ; i < 40 ; i++ ) printf(-); printf(\n); }

Illustration of the use of C functions


Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 2 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

The main functions calls the user-defined printline function two times and the library function printf once. We may notice that the printline function itself calls the library function printf 39 times repeatedly. Any function can call any other function. In fact, it can call itself. A called function can also call another function. A function can be called more than once. In fact, this is one the main features of using functions. Except the starting point, there are no other pre-determined relationships, rules of precedence or hierarchies among the functions that make up a complete program. The functions can be placed in any order. A called function can be placed either before or after the calling function. However it is the usual practice to put all the called functions at the end (Modular programming).
mian () { ..... ..... ..... function1(); ..... ..... function2(); ..... ..... function1(); ..... }

function1 () { ..... ..... ..... } function2 () { ..... function3 (); ..... } function3 () { ..... ..... ..... }

Figure: Flow control in a multi-function program.


Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 3 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

Modular Programming Modular Programming is a strategy applied to the design and development of Software systems. It is defined as organizing a large program into small, independent programs segments called modules that are separately named and individually callable program units. These modules are carefully integrated to become a software system that satisfies the system requirements. It is basically a Divide-and-Conquer approach to problem solving. In C, each module refers to a function that is responsible for a single task. Characteristics of modular programming: Each module should do only one thing. Communication between modules is allowed only by a calling module. A module can be called by one and only one higher module. No communication can take place directly between modules that do not have calling-called relationship. All modules are designed as single-entry, single-exit systems using control structures.

Elements of User-Defined Functions:


Functions are classified as one of the derived data types in C, therefore define functions and use them like any other variables in C programs. Similarities between functions and variables in C: Both function names and variable names are considered identifiers and must follow the rules same as identifiers. Like variables, functions have types associated with them. ( such as int, float, ) Like variables, functions names and their types must be declared and defined before they are used in a program. In order to make use of a user-defined function, we need to establish three elements that are related to functions. 1. Function Definition: An independent program module, specially written to implement the requirements of the function. 2. Function Call: Used to invoke function at a required place in the program. 3. Function Declaration / Prototype: Like declaration of a variable, function should be declared to use later in the program.
Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 4 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

#include <stdio.h> void add(); void main() { add(); } Function Declaration Function Call

Function void add() Definition { int a = 10, b = 15, sum ; sum of + b ; Definitions = a Functions: printf(\n Sum of 10 + 15 = %d, sum); It} also known as Function Implementation, include the following elements, is Function Name Function Type List of Parameters Local Variable Declarations Function Statements A return Statement Function Header ( The First Three Elements ) & Function Body ( The Second Three Elements ) The general format of a function definition to implement above two parts is given below: function_type function_name( parameter list ) { local variable declaration ; executable statement1 ; executable statement2 ; ..... ..... return statement ; }
Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 5 of 27

Function Header

Function Body

All the six elements are mainly grouped into two parts, namely,

Function Elements

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

The first line f u n c t i o n _ t y p e

f u n c t i o n _ n a m e ( p a r a m e t e r l i s t ) is

known as the Function Header and the statements within the opening and closing braces constitute the function body, which is compound statement. FUNCTION HEADER: It has three parts, The Function Type / Return Type The Function Name and The Formal Parameter The Function Type / Return Type: It specifies the type of value ( like int, float or double ) that the function is expected to return to the program calling the function. If the return type is not explicitly specified, C will assume that it is an integer type by (default) i.e., default return type is integer for unspecified function type. If the function is not returning anything, then we need to specify the return type as void. It is a good practice to code explicitly the return type, even when it is an integer. The value returned is the output produced by the function. The Function Name: It is any valid C identifier or variable names, the name should be appropriate to the task performed by the function. Avoid duplicating library routine names or operating system commands. The Formal Parameter List It declares the variables that will receive the data sent by the calling program/function. It serves as input data to the function to carry out the specified task. They represent actual input values. The parameters are also known as arguments. The parameter list contains declaration of variables separated by commas and surrounded by parentheses. Examples: float quadratic ( int a, int b, int c) {..} double power ( double x, int n ) {..} float mul ( float x, float y) {..} int sum ( int a, int b ) {..}

Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 6 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

Remember, there is no semicolon after the closing parenthesis and the declaration of parameter variables cannot be combined. Example: int sum ( int a, b ) is illegal. A function need not always receive values from the calling program, in such cases, functions have no formal parameters, and then we use void between the parentheses as in void printline (void) or void printline ( ) { ..... ..... } This function neither receives any input values nor returns back nay value. It is a good programming style to use void to indicate a null parameter list. FUNCTION BODY: It has three parts, This contains the declaration and statements necessary for performing the required task, enclosed in braces, contains three parts, in the below order: 1. Local Declarations that specify the variables needed by the function. 2. Function Statements that perform the task of the function. 3. A Return Statement that returns the value evaluated by the function. If a function does not return any value, we can omit the return statement. However, note that its return type should be specified as void. Again, it is nice to have a return statement even for void function. NOTE When a function reaches its return statement, the control is transferred back to the calling program. In the absence of a return statement, the closing brace acts as a void return. return. A local Variable is a variable that is defined inside a function and used without having any role in the communication between functions.

Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 7 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

Return Values and Their Types:


A function may or may not send back any value to the calling function. If it does, it is done through the return statement. It is possible to pass to the called function any number of values; the called function can only return one value per call, at the most. The return statement can take one of the following forms

return;
Example:

/* plain return does not return any value, the control is immediately */ if(error) return;

passed back to the calling function when a return is encountered.

return(expression);
Example:

/* returns the value of the expression */

int add(int a, int b) { return(a+b); } All functions by default return int type data. One can force a function to return a particular type of data by using a type specifier in the function header. When a value is returned, it is automatically cast to the functions type. For instance, the function int product (void) { return ( 2.5 * 3.0 ) ; } will return the value 7, only the integer part of the result. The return value will be truncated to an integer.

Function Calls:
A function can be called by simply using the function name followed by a list of actual parameters or arguments, if any enclosed in parentheses. Example: main() { int y; y = mul(10,5); printf(%d\n,y); /* Function Call */

} When the compiler encounters a function call, the control is transferred to the function mul(). This function is then executed line by line as described and a value is returned when a return statement is encountered. This value is assigned to y.
Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 8 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

main() { int y; y = mul(10,5) ; /* call */ } int mul ( int x, int y ) { int p; p=x*y; return (p); The function call sends two integer values}10 & 5 to the function. int mul(int x, int y) which are to x = 10 and y = 5 respectively. The function computes the product x and y , assigns the result to the local variable p, and then returns value 25 to the main where it is assigned to y . There are different ways to call a function. mul() function can be invoked: mul(10,5) mul(m,5) mul(10,n) mul(m,n) mul(m+5,10) mul(10,mul(m,n)) /* uses its own call as its one of the parameter */ mul(expresssion1 ,expression2) /*expression should be evaluated to single values that can be passed as actual parameters. */ A function which returns a value can be used in expression like any other variable. Example: printf(%d\n, mul(p,q)); y = mul(p,q) / ( p+q) ; if (mul(m,n) > total ) printf(%d, max ); A function cannot be used as mul(a,b) = 15 ; is invalid. /* local variable */ /* x = 10 , y = 5 */

A function that does not return any value may not be used in expressions, but can be called in to perform certain tasks specified in the function. Example: main() { printline(); /* Note that the presence of a semicolon at the end */ }
Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 9 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

Function Call A function call is a postfix expression. When a function call is used as a part of an expression, it will be evaluated first, unless parentheses are used to change the order of precedence. In a function call, the function name is the operand and the parentheses set (..) which contains the actual parameters is the operand. The actual parameters must match the functions formal parameters in type, order and number. Multiple actual parameters must be separated by commas. Note: 1. If the actual parameters are more than the formal parameters, the extra actual arguments will be discarded. 2. If actual parameters are less than the formal parameters, the unmatched formal arguments will be initialized to some garbage. 3. Any mismatch I data types may also result in some garbage values.

Function Declaration: also known as Function Prototype


Like variables, all functions in a C program must be declared, before they are invoked. A function declaration consists of four parts. Function Type ( Return Type ) Function Name Function Parameter List Terminating Semicolon, in the following format: function-type function-name ( parameter list ); It is similar to the function header line except the terminating semicolon. Example : int mul ( int x, int y ) ; /* Function Prototype */ Important Note: 1. The parameter list must be separated by commas. 2. The parameter names do not need to be the same in the prototype declaration and the function definition. 3. Use of parameter names in the declaration is optional. 4. If the function has no formal parameters, the list is written as (void). Example: void print_line(void) { . . .} 5. The return type is optional, when the function returns int type data. 6. The return type must be void if no value is retuned. 7. When the declared types do not match with the types in the function definition, compiler will produce an error. Example: (Valid/Acceptable) mul ( int, int); mul ( int x, int y);
Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 10 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

int mul ( int, int); When a function does not take any parameters and does not return any value, its prototype is written as: void function_name (void) ; A prototype declaration may be placed in two places: 1. Above all the functions ( including main() ) ; /* In the global declaration section, referred as a global prototype , available for all function in the program. */ 2. Inside a function definition ; /* in the local declaration section, referred as a local prototype , are used by the functions containing them */ The place of declaration of a function defines a region in a program in which the function may be function may be used by other functions. This region is known as the scope of the function. It is good programming style to declare prototypes in the global declaration section before main(). It adds flexibility, provides an excellent quick reference to the functions used in the program, and enhances documentation (readability). Proto Types: Yes / No Prototype declarations are not essential. If a function has not been declared before it is used, C will assume that its details available at the time of linking. If these assumptions are wrong, the linker will fail. The moral is that we must always include prototype declarations, preferably in global declaration section. Parameters also known as Arguments 1. 2. 3. Are used I three places; In Declaration ( Prototype ) : are called Formal Parameters In Function Call : are called Actual Parameters In Function Definition : are called Formal Parameters Actual Parameters used in a calling statement may be simple constants, variables or expressions. The formal and actual parameters must match exactly in type, order, and number. Their names do not need to match.

Category of Functions:
A function, depending on whether arguments are present or not and whether a value is returned or not, may belong to one of the following categories: Category-1: Category-2: Category-3: Category-4: Category-5: Functions with no arguments and no return values. Functions with arguments and no return values. Functions with arguments and one return value. Functions with no arguments and but return a value. Functions that return multiple values.

Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 11 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

No Arguments and No Return Values:


When a function has no arguments, it does not receive any data from the calling function. Similarly, when it does not return a value, the calling function does not receive any data from the called function. In effect, there is no data transfer between the calling function and the called function. This indicates that there is only a transfer of control but no data. fucntion-1( ) { ..... ..... function-2( ); ..... ..... }
Calling Function

Control / No Input

Control / No Output

fucntion-2( ) { ..... ..... ..... ..... ..... }


Called Function

Figure: No data communication between functions Note: A function does not return any value cannot be used in the expression. It can only be used as an independent statement. When there is nothing to be returned, the return statement is optional. The closing brace of the function signals the end of execution of the function, thus returning the control, back to the calling function.

Arguments but No Return Values:


The calling function has no control over the way the functions receives input data. We could make the calling function to read data from the terminal and pass it on to the called function. The calling function can check for the validity of data, if necessary, before it is handed over to the called function. fucntion-1( ) { ..... ..... function-2(a); ..... ..... } fucntion-2(x) { ..... ..... ..... ..... ..... }

Control / Values of Arguments

Control / No Return Value

Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 12 of 27

C 110/101 S A lgorithm A ic pproach to P roblemS olving Calling Function

Called Function

Figure: One-way data communication between functions The actual and formal arguments should match in number, type and order. The values of actual arguments are assigned to the formal arguments on a one to one basis, staring with the first arguments.

Function Call

main( ) { ..... Actual Arguments function-1 ( a1, a2,a3, . . . , an ) ; ..... } function-1( ) { ..... function-1 ( A1, A2,A3, . . . , An ) ;

... . Formal Arguments Figure: Arguments matching. between the function call and the called function } Ensure that the function call has matching arguments. In case, the actual arguments are more than the formal arguments ( an > An ), the extra actual arguments are discarded. On the other hand, If the actual arguments are less than the formal arguments, the unmatched formal arguments are initialized to some garbage values. Any mismatch in data type may also result in passing of garbage values without generating the error message. Remember that, when a function call is made, only a copy of the values of actual arguments is passed into the called function. What occurs inside the function will have no effect on the variables used in the actual arguments list. Variable Number of Arguments Some functions have a variable number of arguments and data types which are not known at compile time (Example: printf and scanf functions). The ANSI standard proposes new symbol called the ellipsis to handle such functions. The ellipsis consists of three period(...) and used as double interest ( float p,) Both the function declaration and function definition should use ellipsis to indicate that the arguments are arbitrary both in number and type.
Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 13 of 27

Calling Function

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

Arguments with Return Values:


To ensure a high degree of portability between programs, a function should generally be coded without involving any I/O operations. For instance, different programs may require different output formats fro display of results. This shortcoming can be overcome by handling over the result of a function to its calling function where the returned value can be used as required by the program. The self-contained and independent function should behave like a black box that receives a predefined form of input and outputs a desired value. Such functions will have two-way data communication. fucntion-1( ) { ..... ..... z = function-2(a); ..... ..... }
Calling Function

Control / Values of Arguments

Function Result / Return Value

fucntion-2(x) { ..... ..... ..... ..... return ( y ); }


Called Function

Figure: Two-way data communication between functions If we have mismatch between type of data that the called function returns and the type of data that the calling function expects, we will have unpredictable results. Be very careful to make sure that both types are compatible.

No Argument but Returns a Value:


There could be some situations where we may need to design functions that may not take any arguments but returns a value to the calling function. A typical example is the getchar library function declared in the header file <stdio.h>. Example:
int getnum(void); main() { int m = get_num( ) ; printf(%d, m); } int get_num(void) { int n; scanf(%d, &n); return (n) ; }

Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 14 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 15 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

Functions that Returns Multiple Values:


We have studied functions that return just one value using a return statement. That is because; a return statement can return only value. Suppose, however, that we want to get more information. We can achieve this in C using the arguments not only to receive information but also to send back information to the calling function. The arguments that are used to send out information are called output parameters. The mechanism of sending back information through arguments is achieved using the Address Operator ( & ) and Indirection Operator ( * ). Example: swapping the content of Two Numbers

#include <stdio.h> void swapXY(int *x, int *y); main() { int x = 55 , y = 75 ; swapXY( &x, &y ) ; printf(%d %d, x, y ); }
Calling Function

void swapXY(int *a, int *b) { int temp ; temp = *a ; *a = *b ; *b = temp ; }


Called Function

Figure: Two-way data communication between functions The operator * is known as indirection operator because it gives an indirect reference to a variable through its address. The use of pointer variables as actual parameters for communicating data between functions is called Pass by Pointers or Call by Pointers. Rules for Pass by Pointers 1. The type of the actual and formal arguments must be same. 2. The actual arguments (in the function call) must be the address of variables that are local to the calling function. Example: swapXY ( int &X, int &Y ) ; 3. The formal arguments in the function header must be prefixed by the indirection operator * . Example: void swapXY ( int *X, int *Y ) { } 4. In the prototype, the arguments must be prefixed by the symbol * . Example: void swapXY ( int *X, int *Y ) ; or void swapXY ( int*, int* ) ; 5. To access the value of an actual argument in the called function, we must use the corresponding formal argument prefixed with the indirection operator * . Example: temp = *X ; *X = *Y ; *Y = temp ;
Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 16 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

Passing Parameters to Functions:


The called function receives the information form the calling function through the parameters. The variables used while invoking the called function are called actual parameters. And the variables used in the function header of called function are called formal functions. There are two types of passing parameters to the functions: 1. Pass by value ( Call by Value ) 2. Pass by Pointers (Call by Pointers / Address / Reference) Pass by Value (Call by Value): When a function is called with actual parameters, the values of actual parameters are copied into formal parameters. If the value of the formal parameters changes in the function, the values of the actual parameters are not changed. Note: In pass by value (call by value) any change done on formal parameters will not affect the actual parameters. Pass by Pointers / Address / Reference (Call by Pointers): In pass by reference, a function is called with address of actual parameters. In the function header, the formal parameters receives the address of actual parameters. Now, the formal parameters do not contain values, instead they contain addresses. any variable that contains an address is called a pointer variable. Using pointer variables, the value of the actual parameters can be changed. Note: In pass by reference (call by reference) any change done on actual parameters indirectly using will affect the actual parameters. This way of changing the actual parameters using formal parameters is called pass by reference or call by reference. (Call by Value versus Call by Reference/Pointers/Address) The technique used to pass data from one function (Calling) to another (Called) function is known as parameter passing. There are two ways of parameter passing: 1. Pass by Value ( or Call by Value ) 2. Pass by Pointers ( or Call by Pointers / References / Address ) In Pass by Value ( or Call by Value ) , values of actual parameters are copied to the variables in the parameter (Formal) list of the called function. The called function works on the copy and not on the original values of the actual parameters. This ensures that the original data in the calling function cannot be changed accidentally.
Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 17 of 27

Pass by Value versus Pass by Pointers

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

In Pass by Pointers ( or Call by Pointers / References / Address ), the memory addresses of the variables rather than the copies of values are send to the called function. The called function directly works on the data in the calling function and the changed values are available in the calling function for its use. This method is used when manipulating arrays and strings. And also used when multiple values to be returned by the called function.

Nesting of Functions:
C permits nesting of functions freely. main can call function-1, which calls function-2, which calls function-3,. . .,and so on.there is in principle no limit as to how deeply functions can be nested. Nesting of function calls is also possible. For example: GCD = gcd( a, gcd( b , c) ); /* GCD of three integers */ add_matrices ( add_matrices ( a, b ), c ); /* Sum of Three Matrices a, b & c */ Note: The nesting dos not mean defining one function within another.

Recursion: It is special case of process, where a function calls itself. It can be


effectively used to solve problems, where solution is expressed in terms of successively applying the same solution to subsets of the problem. In recursive functions, we must have an if statement somewhere to force the function to return without the recursive call being executed. Otherwise, the function will never return. Example: Factorial of n = n(n-1)(n-2).1 factorial ( int n ) { int fact; if ( n == 1 ) return (1); else fact = n * factorial ( n 1 ) ; return ( fact ); }

Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 18 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

Passing Arrays to Functions:


One-Dimensional Arrays: To pass a one-dimensional an array to a called function, it is sufficient to list the name of the array, without any subscripts, and the size of the array as arguments. Example: big = largest ( a, n) ; will pass the whole array a to the called function. The called function expecting this call must be appropriately defined. The largest function header might be int largest ( int array[] , int size ) The declaration of the formal argument array is made as int array[]; In C, the name of the array represents the address of its first element. By passing the array name, we are, in fact, passing the address of the array to the called function. The array in the called function now refers to the same array stored in the memory. Therefore, any change in the array in the called function will be truly reflected in the original array. Passing addresses of the parameters to the functions is referred to as pass by address or pass by pointers or pass by reference. Note: We cannot pass a whole array by value as we did in the case of ordinary variables. Rules to Pass an Array to a Function 1. The function must be called by passing only the name of the array. 2. In the function definition, the formal parameter must be an array type; the size of the does not need to be specified. 3. The function prototype must show the argument is an array. Two-Dimensional Arrays: Like simple arrays, we can also pass multi-dimensional arrays to functions. It is similar to the one-dimensional arrays. The rules are simple. 1. The function must be called by passing only the array name. 2. In the function definition, we must indicate that the array has two dimensions by including sets of brackets ( i.e., [] [] ) 3. The size of second dimension must be specified. 4. The prototype declaration should be similar to the function header. Example: trace_matrix(a, m, n) ; /* Function Call */ trace_matrix(int array[][n], int m, int n) /* Function Header / Function Definition */ trace_matrix(int array[][n], int m, int n) /* Function Declaration / Prototype */
Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 19 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

Passing Strings to Functions:


The strings are treated as character arrays in C, the rules for passing strings to functions are very similar to those for passing arrays to functions. Like arrays, strings in C cannot be passed by values to functions. Example: void display ( char item_name[] ) /* Function Definition */ void display ( char str[] ) ; /* Function Declaration */ display ( names ) ; /* Function Call */ where name must be properly declared in the calling function. char name [15] ; Programming Examples
/* Program : B15.C Write C User Defined Functions (i) To input N integer numbers into a single dimension array. (ii) To conduct a Linear Search. Using these functions, write a C program to accept the N integer numbers and given key integer number and conduct a Linear Search. Report success or failure in the form of a suitable message.

*/ #include <stdio.h> #include <process.h> #define SIZE 10 int a[SIZE];

/* Global Declaration */

void input(int); /* Function Declaration / Prototype */ void linear_search(int, int);/* Function Declaration / Prototype */ main() { int n, key; clrscr(); printf("\nEnter the size of list : "); scanf("%d", &n); input(n); /* Function Call, which reads N elements of the list */

printf("\nEnter the key element to be searched in the list : "); scanf("%d", &key); linear_search(n,key); } getch();

void input(int n) /* Function - input() */ { int i; printf("\nEnter the %d elements : ",n); for(i=0 ; i<n ; i++) scanf("%d", &a[i]); return; /* transfer control to the main/calling function */

Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 20 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving


/* Function - linear_search() */

void linear_search(int n, int key) { int i;

} /*

for(i=0 ; i<n ; i++) { if(a[i] == key) { printf("\nSearch Successful, Key found at position %d", i+1); getch(); exit(0); } } printf("\nKey Not found / Search Failed..."); return; /* transfer control to the main/calling function */ Program : B16.C Write C User Defined Functions (i) To input N integer numbers into a single dimension array. (ii) To sort the integer numbers in ascending order using BUBBLE SORT technique. (iii) To print the single dimension array elements. Using these functions, write a C program to input N integer numbers into a single dimension array, sort them in a ascending order, and print both the given array and the sorted array with suitable headings.

*/

#include <stdio.h> #include <process.h> #define SIZE 10 int a[SIZE]; /* Global Declaration */

void input(int); /* Function Declaration / Prototype */ void bubble_sort(int); /* Function Declaration / Prototype */ void print_sorted(int); /* Function Declaration / Prototype */ main() { int n; clrscr(); printf("\nEnter the size of list : "); scanf("%d", &n); printf("\nEnter the %d elements to Sort : ",n); input(n); /* Function call for Bubble Sort */ bubble_sort(n); printf("\nThe Sorted elements using Bubble Sort Method :"); print_sorted(n); } getch();

void input(int n) /* Function - input() */ { int i; for(i=0 ; i<n ; i++) scanf("%d", &a[i]); return; /* transfer control to the main/calling function */

void bubble_sort(int n) { int i,j,k, temp;

Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 21 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

for(j=1 ; j<n ; j++) { for(i=0 ; i<n-j ; i++) { if(a[i] >= a[i+1]) { temp = a[i] ; a[i] = a[i+1] ; a[i+1] = temp ; } } printf("\nPartial sorted elements after %d pass \n",j); for(k=0 ; k<n ; k++) printf("%d ", a[k]); printf("\n"); } return; /* transfer control to the main/calling function */ /* Function - input() */

void print_sorted(int n) { int i;

} /*

for(i=0 ; i<n ; i++) printf("\n%d", a[i]); return; /* transfer control to the main/calling function */

Program : B17.C Write C User Defined Functions (i) To input N integer numbers into a single dimension array. (ii) To sort the integer numbers in ascending order using SELECTION SORT technique. (iii) To print the single dimension array elements. Using these functions, write a C program to input N integer numbers into a single dimension array, sort them in a ascending order, and print both the given array and the sorted array with suitable headings.

*/

#include <stdio.h> #include <process.h> #define SIZE 10 int a[SIZE]; void input(int); void selection_sort(int); void print_sorted(int); main() { int n; clrscr(); printf("\nEnter the size of list : "); scanf("%d", &n); printf("\nEnter the %d elements to Sort : ",n); input(n); /* Global Declaration */ /* Function Declaration / Prototype */ /* Function Declaration / Prototype */ /* Function Declaration / Prototype */

Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 22 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

/* Function call for Selection Sort */ selection_sort(n); printf("\nThe Sorted elements using Selection Sort Method :"); print_sorted(n); } getch();

void print_sorted(int); void input(int n) /* Function - input() */ { int i; for(i=0 ; i<n ; i++) scanf("%d", &a[i]); return; /* transfer control to the main/calling function */

void selection_sort(int n) { int i,j,k,pos,temp; for(j=0 ; j<n-1 ; j++) { pos = j; for(i=j+1 ;i<n ;i++) if(a[i] < a[pos]) pos = i; temp = a[pos] ; a[pos] = a[j] ; a[j] = temp ; printf("\nThe Partial sorted list after %d PASS :\n",j+1); for(k=0;k<n;k++) printf("%d ",a[k]); printf("\n"); /* transfer control to the main/calling function */ /* Function - input() */

} return;

void print_sorted(int n) { int i;

} /*

for(i=0 ; i<n ; i++) printf("\n%d", a[i]); return; /* transfer control to the main/calling function */

*/

Program : B18.C Write C User Defined Functions (i) To input N real numbers into a single dimension array. (ii) Compute their MEAN. (iii) Compute their VARIANCE. (iv) Compute their STANDARD DEVIATION. Using these functions, write a C program to input N real numbers into a single dimension array, and compute their mean, variance and standard deviation. Output the computed results with suitable headings.

#include <stdio.h> #include <math.h> #include <process.h>

Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 23 of 27

C 110/101 S
int i, n; float x[10], sum, m, v, d; void input(); float mean(); float varinace(); void sd(); main() { clrscr();

A lgorithm A ic pproach to P roblemS olving


/* Global Declaration */ /* Global Declaration */

/* Function Declaration / Prototype */ /* Function Declaration / Prototype */ /* Function Declaration / Prototype */ /* Function Declaration / Prototype */

printf("\nEnter the size of N : "); scanf("%d", &n); printf("\nEnter the %d real values to compute their Standard Deviation : \n",n); input(); /* Function to read N real numbers */ sd(); /* Function call to compute Standard Deviation */ getch();

/* Function to read N values */ void input() { for(i=0 ; i<n ; i++) scanf("%f", &x[i]); } /* Function to find STANDARD DEVIATION */ void sd() { d = (float) sqrt(varinace()) ; printf("\nStandard Deviation : \t%f\n",d); } /* Function to return VARIANCE value */ float varinace() { m = mean(); sum = 0; for(i=0 ; i < n ; i++) sum = sum + pow((x[i]-m),2); v = sum / n; printf("\nThe VARIANCE\t : \t%f",v); } return v;

/* Function to return MEAN value */ float mean() { sum = 0; for(i=0 ; i<n ; i++) { sum = sum + x[i] ; } m = sum / n; printf("\nThe MEAN (Average) : \t%f",m); } return m;

Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 24 of 27

C 110/101 S
/*

A lgorithm A ic pproach to P roblemS olving

Program : B19.C Write C User Defined Functions: (a) To read the elements of a given matrix of size M x N. (b) To print the elements of a given matrix of size M x N. (c) To compute the product of two matrices. Using these functions, write a C program to read two matrices A(MxN) and B(PxQ) and compute the product of A and B after checking compatibility for multiplication. Output the input matrices and the resultant matrix with suitable headings and format. (Using two dimension arrays where array size M,N,P,Q <= 3)

*/

#include <stdio.h> #define SIZE 5 void read_matrix(int [][], int, int); void product_matrix(int [][],int [][], int [][], int, int, int); void write_matrix(int [][], int, int); int i, j, k; main() { int m, n, p, q, a[SIZE][SIZE], b[SIZE][SIZE], c[SIZE][SIZE]; clrscr(); printf("\nEnter the Size of 2-Dimension Arrays i.e., M,N,P,Q <= 3 Only..."); printf("\nEnter the Size of 2-Dimension Array-A : "); scanf("%d %d", &m, &n ); printf("\nEnter the Size of 2-Dimension Array-B : "); scanf("%d %d", &p, &q ); if ( n != p ) { printf("\nInvalid array size, Multiplication is not possible..."); getch(); exit(0); } read_matrix(a,m,n); read_matrix(b,p,q); /* Function call to read MATRIX-A */ /* Function call to read MATRIX-B */

product_matrix(a,b,c,m,n,q); printf("\nElements of MATRIX-A : \n"); write_matrix(a,m,n); printf("\nElements of MATRIX-B : \n"); write_matrix(b,p,q); printf("\nThe resultant MATRIX-C of size %d x %d : \n",m,q); printf("\nThe Product of two matrices :\n"); write_matrix(c,m,q); } void read_matrix(int x[][SIZE], int y, int z) /* Function to read MATRIX */ { printf("\nEnter the %d elements to the 2-D Array-A : \n", y*z); for(i=0; i<y ; i++) { for(j=0; j<z ; j++) { scanf("%d", &x[i][j]); } } } void product_matrix(int a[][SIZE], int b[][SIZE], int c[][SIZE], int m, int n, int q) with MAT-B, assigns result to the MAT-C */ /* Multiplication of MAT-A

Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 25 of 27

C 110/101 S
{

A lgorithm A ic pproach to P roblemS olving

for(i=0; i<m ; i++) { for(j=0; j<q ; j++) { c[i][j] = 0 ; for(k=0 ; k<n ; k++) { c[i][j] = c[i][j] + a[i][k] * b[k][j] ; } } }

} void write_matrix(int c[][SIZE], int m, int q) /* Function to Display 2-D Matrix */ { for(i=0; i<m ; i++) { for(j=0; j<q ; j++) { printf("%d ", c[i][j]); } printf("\n"); } } /* getch();

*/

Program : B20.C Write a C program to read a matrix A(MxN) and to find the following using User Deifned Functions: (a) Sum of the elements of the specified row. (b) Sum of the elements of the specified column. (c) Sum of all the elements of the matrix. Output the computed results with suitable headings.

#include <stdio.h> #define SIZE 5 int i, j, a[SIZE][SIZE]; void accept_matrix(int, int); void print_matrix(int, int); int row_sum(int, int); int col_sum(int, int); int matrix_sum(int, int); main() { int m, n, col, row, rsum, csum, trace; clrscr(); printf("\nEnter the Size of 2-Dimension MATRIX i.e., M & N <= 3 Only..."); printf("\nEnter the order of 2-Dimension MATRIX-A : "); scanf("%d %d", &m, &n ); printf("\nEnter the %d elements to the 2-D MATRIX : \n", m*n); accept_matrix(m,n); /* Function call to read MATRIX */ printf("\nThe Given MATRIX is : \n"); print_matrix(m,n); /* Function call to Print MATRIX */

Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 26 of 27

C 110/101 S

A lgorithm A ic pproach to P roblemS olving

} void accept_matrix(int y, int z) /* Function to read MATRIX */ { for(i=0; i<y ; i++) for(j=0; j<z ; j++) scanf("%d", &a[i][j]); } void print_matrix(int y, int z) /* Function to Print MATRIX */ { for(i=0; i<y ; i++) { for(j=0; j<z ; j++) { printf("%d ", a[i][j]); } printf("\n"); } } int row_sum(int row, int n) /* Function to sum specifed ROW */ { int rsum = 0; for(j=0; j<n ; j++) { rsum = rsum + a[row-1][j] ; } return rsum; } int col_sum(int m, int col) /* Function to sum specifed COLUMN */ { int csum = 0; for(i=0; i<m ; i++) { csum = csum + a[i][col-1] ; } return csum; } int matrix_sum(int m, int n) /* Function to sum of all elements */ { int sum = 0; for(i=0; i<m ; i++) for(j=0 ; j<n ; j++) sum += a[i][j]; return sum; }

a: printf("\nEnter the ROW number less than %d to find its Sum : ",m+1); scanf("%d",&row); if(row>m) { printf("\nThe ROW number should not be greater than %d ",m); goto a; } rsum = row_sum(row,n); printf("\nSum of the elements of ROW-%d = %d\n",row,rsum); b: printf("\nEnter the COLUMN number less than %d to find its Sum : ",n+1); scanf("%d",&col); if(col>n) { printf("\nThe COLUMN number should not be greater than %d ",n); goto b; } csum = col_sum(m,col); printf("\nSum of the elements of COLUMN-%d = %d\n",col,csum); trace = matrix_sum(m,n); printf("\nThe sum of all elements of the given MATRIX : %d",trace); getch();

Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 27 of 27

Das könnte Ihnen auch gefallen