Beruflich Dokumente
Kultur Dokumente
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.
These
C 110/101 S
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
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); }
C 110/101 S
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 () { ..... ..... ..... }
C 110/101 S
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.
C 110/101 S
#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
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
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
return;
Example:
/* plain return does not return any value, the control is immediately */ if(error) return;
return(expression);
Example:
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
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
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.
C 110/101 S
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
Control / No Input
Control / No Output
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.
Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 12 of 27
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
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.
Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 14 of 27
C 110/101 S
Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 15 of 27
C 110/101 S
#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
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
C 110/101 S
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.
Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 18 of 27
C 110/101 S
C 110/101 S
/* 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
} /*
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 */
Divakara N (DN), Dept. of Computer Science & Engineering, SJCE, Mysore-06 Page 21 of 27
C 110/101 S
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() */
} /*
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
/* 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;
} /*
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.
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();
/* 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
/*
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
{
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
} 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