UNIT – IV – FUNCTIONS 1. FUNCTION Function is a group of statements that perform a specific task and is relatively independent of the remaining code. Functions are used to organize programs into smaller and independent units 2. ADVANTAGES OF MODULARIZING A PROGRAM INTO FUNCTIONS  Reduction in code redundancy  Information hiding  Enabling code reuse  Improved debugging & Testing  Better Readability  Improved maintainability 3. FUNCTIONS ARE CLASSIFIED ACCORDING TO THE FOLLOWING CRITERIA 1. Based upon who develops the function 2. Based upon the number of arguments a function accepts When the program is 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. These independently coded programs are called functions that are much easier to understand, debug and test. 4. CLASSIFICATION OF FUNCTIONS – BASED UPON WHO DEVELOPS THE FUNCTION Based upon who develops the function, functions are classified as 1. User defined functions 2. Library Functions 5. USER DEFINE FUNCTION User defined functions are the functions that are defined or developed by the user at the time of writing a program. User defined function sometimes referred to as Programmer – defined functions. We can define functions and use them like any other variables in C Programs

Both function names and variable names are considered as identifiers. Like variable functions have types associated with them. Like variables function names and their types must be declared and defined before they are used in a program. 5. 1. Elements of a function  Function declaration  Function Call  Function definition 5. 2. Function declaration or prototype The calling program should declare any function that is to be used later in the program. SYNTAX function_type function_name( parameter type list );  Function_ Type :- return type which is an optional filed. Return type can be any type – char, int, float, char *, void except array type and function type.  Function_Name :- it is an identifier. All syntactic rules described fro writing identifier names are applicable for writing the function names as well. Also called as function designator.  Parameter_List :- Must be separated by commas. Parameter names do not need to be the same in the prototype declaration and the function definition. Type must match the types of the parameters in the function definition, in the number and the order. No two parameters list can be the same.  ; Semicolon :- function declaration is a statement, so it must be terminated with a semicolon. A prototype declaration may be placed in two places in a program. 1. Above all functions including main – global Prototype 2. Inside a function definition – local prototype. Only used by the function containing them. 5. 3. Function definition ( Function implementation ) Consists of two parts 1. Function Header and 2. Function body Syntax return_type function_name ( parameter list ) { Local variable declaration;

Executable statement 1; Executable statement 2; … … Executable statement n; return statement }  return_type :- it is optional. It is type of value that the function is expected to return to the program calling the function. If return type is not explicitly specified, C will assume that it is an integer type. If the function is not returning anything the return type is void.  Function_name :-valid C identifier. Should be follow the same rules as identifier.  Parameter list :- declares the variable that will receive the data sent by the calling program. They serve as input data to the function to carry out the specified task.  A function need not always receive values from the calling program. In such cases use the keyword void between the parenthesis. 5. 4. Function body  Contains the declarations and statements necessary for performing the required task.  Local declaration specifies the variables needed by the function.  Function statements that perform the task of the function  A return statement that returns the value evaluated by the function  If a function does not return any value, we can omit return statement.  No two parameter names appearing in the parameter list can be the same.  Return type and the number and types of parameters in the function header should exactly match the corresponding return types and the number and types of parameters in the function declaration.  It is not mandatory to have the same names for the parameters in the function declaration and function definition.  The header of the function is not terminated with a semicolon. 5. 5. Function Call A function can be called by simple using the function name followed by a list of actual parameters ( if any ) enclosed in parenthesis.

When the compiler encounters a function call, the control is transferred to the function. The function is then executed line by line as described and a value is returned when a return statement is encountered. 5. 6. Return Statement Used to return the result of the function to the calling function. Two types 1. return - does not return any value. The control is immediately passed back to the calling function. This type cannot be used inside a function whose return type is not void. 2. return (expression) – return control along with result to calling program. This type cannot be used when the return type is void. The return expression may be simple expression, complex expression or function call. Return type and type of the result of evaluation of a return expression must be same. Example //Program to implement Function #include #include void main() { int a, b, c; int add(int, int); // Function Declaration clrscr(); printf("\Enter he two numbers "); scanf("%d%d",&a,&b); c=add(a,b); // Function Call - a and b are actual arguments printf("%d + %d = %d",a,b,c); getch(); } // Function Defintion int add(int x, int y)

// Function Header

{ int z;

// Function Body

z= x+y; return z;

// Return Statement

} Sample Input Output Enter he two numbers 12 34 12 + 34 = 46

ELEMENTS OF USER-DEFINED FUNCTIONS In order to write an efficient user defined function, the programmer must familiar with the following three elements. a. Function definition b. Function declaration c. Function call 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 declaration: Like the normal variables in a program, the function can also be declared before they are defined and invoked. c. Function Call: The function can be called by simply specifying the name of the function, return value and parameters if presence.

Briefly explain about function prototypes with syntax and examples. Function prototypes are classified depending on whether the arguments are present or not and whether a value is returned or not. A prototype statement keeps the compiler to check the return type and argument types of the function.

Types of prototypes: 

Function with no arguments and no return value.



Function with arguments and no return value.



Function with arguments and with return value.



Function with no arguments and with return value.

Function with no arguments and no return value: 

In this prototype no data transfer takes place between the calling function and the called function.



The called function does not receive any data from the calling function and does not send back any value to the calling function.



They read data values and print the result in the same block.



Syntax: main()

fun1()

{

{ ……

………

fun1();

………

……

………

} 

}

The dotted lines indicate that there is only transfer of control but no data transfer.



Example: #include void main(0 { void add(void); Add(); } void add() { int a,b,c; printf(“Enter two numbers:”); scanf(“%d %d”,&a,&b); c=a+b; printf(“Sum =%d”,c); } OUTPUT: Enter two numbers: 10 20

Sum= 30. o Function with arguments and no return values: 

In this prototype data is transferred from the calling function to the called function.



The called function receives some data from the calling function and does not send back any values to the calling program (one way communication).



Syntax: main()

fun1(x,y)

{

{ ……

………

fun1(a,b);

………

……

………

} 

}

The continuous line indicates data transfer and the dotted line indicates control transfer.



Example: #include void main(0 { 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 =%d”,z); } OUTPUT:

Enter two numbers: 10 20 Sum= 30. o Function with arguments and with return value: 

In this prototype data is transferred between the calling function and the called function.



The called function receives some data from the calling function and sends back some values to the calling function (two way communication).



Syntax: main()

data_type fun1(x,y)

{

{ ……

………

c=fun1(a,b);

………

……

return(z);

} 

}

The continuous line indicates that the data transfer takes place between calling function and the called function.



Example: #include void main(0 { int add(int,int); int a,b,c; printf(“Enter two numbers:”); scanf(“%d %d”,&a,&b); c=add(a,b); printf(“Sum =%d”,c); } int add(int x,int y) { int z; z=x+y; return(z); } OUTPUT: Enter two numbers: 10 20 Sum= 30.

o Function with no arguments and with return value: 

In this prototype the calling function can not pass any arguments to the called function but the called function may send some return value to the calling function.



The called function is independent.



It reads values from the keyboard and returns the result.



Syntax: main()

data_type fun1()

{

{ ……

………

c=fun1();

………

……

return(z);

} } 

Example: #include void main(0 { int add(); c=add(); printf(“Sum =%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 Sum= 30.

NESTING OF FUNCTIONS C permits nesting of functions freely, main can call function1, which called functions2, which calls functions function3 … and so on. There is in principle no limit as to how deeply functions can be nested. PARAMETER PASSING METHODS In ‘C’ language there are two ways that the parameters can be passed to a function, they are i) Call by value ii) Call by reference CALL BY VALUE: When the value is passed directly to the function it is called call by value. In call by value only a copy of the variable is only passed so any changes made to the variable does not reflects in the calling function. Example: #include #include swap(int,int); void main() { int x,y; printf("Enter two nos"); scanf("%d %d",&x,&y); printf("\nBefore swapping : x=%d y=%d",x,y); swap(x,y); getch(); } swap(int a,int b) { int t; t=a; a=b; b=t; printf("\nAfter swapping :x=%d y=%d",a,b); } System Output: Enter two nos 12 34 Before swapping :12 34 After swapping : 34 12

CALL BY REFERENCE: When the address of the value is passed to the function it is called call by reference. In call by reference since the address of the value is passed any changes made to the value reflects in the calling function.

Example: #include #include swap(int *, int *); void main() { int x,y; printf("Enter two nos"); scanf("%d %d",&x,&y); printf("\nBefore swapping:x=%d y=%d",x,y); swap(&x,&y); printf("\nAfter swapping :x=%d y=%d",x,y); getch(); } swap(int *a,int *b) { int t; t=*a; *a=*b; *b=t; } System Output: Enter two nos 12 34 Before swapping :12 34 After swapping : 34 12 COMPARISON BETWEEN CALL BY VALUE AND CALL BY REFERENCE S.NO CALL BY VALUE CALL BY REFERENCE Different memory locations are Same memory location occupied by formal 1. occupied by formal and actual and actual arguments, so there is a saving of arguments. memory location. Any alteration in the value of the Any alteration in the value of the arguments 2. arguments passed is local to the passed is accepted in the calling program. function and is not accepted in the calling program. The usual method to call a function The address of the variable is passed as an 3. in which only the value of the argument. variable is passed as an argument. When a new location is created it is The existing memory location is used 4. very slow. through its address, it very fast. There is no possibility of wrong data There is no possibility of wrong data 5. manipulation since the argument are manipulation since the addresses are used in directly used in an expression. an expression. A good skill of programming is required here.

RECURSION A function that calls itself is known as a recursive function and the phenomena is known as recursion. Recursive functions can be effectively used to solve problems where solution is expresses in terms of successively applying the same solutions to subsets of the problem. When we write recursive functions, we must have if statement somewhere to force the function to return without the recursive call being executed. Otherwise the function will never return. DEFINITION: Recursion is the process of calling the same function itself again and again until some condition is satisfied. This process is used for repetitive computation in which each action is satisfied in terms of a previous result. In order to write a recursive program, the user must satisfy the following. 1. The problem must be analysed and written in recursive form. 2. The problem must have the stopping condition. Syntax: function1() { function1(); }

Example : The problem of finding the factorial of n can be expressed in terms of a similar problem of smaller size as n! = n * ( n – 1 )!. 1. Find factorial of a number given number using recursive function. PROGRAM: #include #include int factorial(int); void main() { int a,f; clrscr(); printf(“Enter the number:”);

scanf(“%d”,&a); f=factorial(a); printf(“The factorial of %d=%d”,a,f); getch(); } int factorial(int x) { if(x==0) return 1; else return (x*factorial(x-1)); } OUTPUT: Enter the number: 5 The factorial of 5=120 2. Find whether the number is prime or not using recursive function. PROGRAM: #include #include int prime(int,int); void main() { int num,p; clrscr(); printf(“Enter the number:”); scanf(“%d”,&num); p=prime(num,num/2); if(p==1) { printf(“%d is a prime number”,num); } else { printf(“%d is not a prime number”);

} getch(); } int prime(int num,int i) { if(i==1) { return 1; } else { if(num%i==0) return 0; else prime(num,i-1); } } OUTPUT: Enter the number: 13 13 is a prime number 3. Find GCD using recursive function. PROGRAM: #include #include int findgcd(int,int); void main() { int n1,n2,gcd; clrscr(); printf(“Enter two number:”); scanf(“%d%d”,&n1,&n2); gcd=findgcd(n1,n2); printf(“GCD : %d and %d is %d”,n1,n2,gcd); getch();

} int findgcd(int x,int y) { while(x!=y) { if(x>y) { return findgcd(x-y,y); } else { return findgcd(x,y-x); } } return x; } OUTPUT: Enter two number: 13 26 GCD : 13 and 26 is 13 4. Find Fibonacci series of a given number using recursive function. PROGRAM: #include #include int fibonacci(int); void main() { int i,n; clrscr(); printf(“Enter the n value:”); scanf(“%d”,&n); printf(“The Fibonacci series is \n”); for (i = 0; i < n; i++) { printf("%d\t%n", fibonacci(i));

} getch(); } int fibonacci(int i) { if(i == 0) { return 0; } if(i == 1) { return 1; } return (fibonacci(i-1) + fibonacci(i-2)); } OUTPUT: Enter the n value: 7 The Fibonacci series is 0 1 1 2 3 5 8 5. Program to find NCR value of the given numbers. PROGRAM: # include # include long fact(int) ; void main() { long i, ncr ; int n, r ; clrscr() ; printf("Enter the value for N : ") ; scanf("%d", &n) ; printf("\nEnter the value for R : ") ; scanf("%d", &r) ; if(n >= r) {

ncr = fact(n) / (fact(n-r) * fact(r)) ; printf("\nThe NCR value is : %ld", ncr) ; } else printf("\nCalculating NCR value is not possible") ; getch() ; } long fact(int i) { long x ; if(i == 0) return 1 ; else { x = i * fact(i - 1) ; return x ; } } OUTPUT: Enter the value for N : 7 Enter the value for R : 5 The NCR value is : 21 Enter the value for N : 5 Enter the value for R : 7 Calculating NCR value is not possible 6. Write a program to demonstrate the tower of Hanoi. PROGRAM: #include void main() { void hanoi(int, char, char, char); int n; printf(“ How many Disk….\n”); scanf(“%d”,&n);

hanoi(n,’L’, ‘R’, ‘C’); } void hanoi (int n, char from, char to, char t) { if (n>0) { hanoi(n-1, from, temp, to); printf(“Move disk %d from %c to %c \n”, n, from, to); hanoi(n-1, temp, to, from); } } OUTPUT: How many Disk….3 Move disk 1 from L to R Move disk 2 from L to C Move disk 1 from R to C Move disk 3 from L to R Move disk 1 from C to L Move disk 2 from C to R Move disk 1 from L to R

POINTERS Pointers are used frequently in C, as they offer a number of benefits to the programmers. They includes The computer’s memory is a sequential collection of storage cells. Each cell, commonly known as a byte, has a number called address associated with it. Typically the addresses are numbered consecutively, starting from zero. A pointer variable is nothing but a variable that contains an address which is a location of another variable in memory. Accessing the address of a variable The address of a variable is determined with the help of address operator &. The operator & immediately preceding a variable returns the address of the variable associated with it. Example : p = &quantity; would assign the location of quantity to the variable. Declaring a pointer variables Since pointer variables contain addresses that belongs to a separate data type, they must be declared as pointers before we use them. Syntax Data_type *pointer_name; This tells the compiler three things about the variable pointer_name 1. The asterisk * tells that the variable pointer_name is a pointer variable. 2. pointer_name needs a memory location. 3. pointer_name points to a variable of type data_type. Example : int *p; - declares the variable p as a pointer variable that points to an integer data type. float *q; - declares q as a pointer to a floating point variable. Initialization of pointer variable The process of assigning the address of a variable to a pointer variable is known as initialization. All uninitialized pointer will have some unknown values that will be interpreted as memory addresses. They may not be a valid address or they may point to some valued that are wrong. Example int quantity;

int *p ; // declaration p = &quantity; // initialization Pointer variable always point to the corresponding type of data. It is possible to combine declaration and initialization of the pointer variable in one step.

valid 1.

Invalid int quantity;

float a,b;

int *p= &quantity;

int *p; p =&a;

2.

int quantity, *p=&quantity;

int *p = &x, x;

Accessing a variable through pointers We can access the value of a variable using the pointer, with the help of * usually known as the indirection operator ( dereferencing operator). Example int a=10; int *p=&a; *p returns the value of the variable a i.e., 10, because p is the address of a. The * can be remembered as ‘value at address’. Example void main() { int a; int *ptr; a=10; ptr=&a; printf("\nThe Value of A is %d",a); printf("\nThe address of A is %p",ptr); printf("\nThe value pointed by the point %d",*ptr); } Output The Value of A is 10 The address of A is FFF4

The value pointed by the point 10

Pointer Expressions C allows us to add integers to or subtract integers from pointers, as well as to subtract one pointer from another. Pointers can also be compared using the relational operators. We may not use pointer in division and multiplication. E.g.

Validity

int a=5, b=10; int *p1=&a,*p2=&b; int y=p2 – p1;

valid 2 ( FFF6 – FFF4 )

p1++

valid answer FFF6 ( FFF4 +1 (1 int = 2 bytes ) )

int y = *p1 * *p2;

valid – output 50

p1 / p2;

Invalid

Pointers and Arrays When an array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations. The base address is the location of the first element of the array. The compiler also defines the array name as a constant pointer to the first element. Suppose we declare an array x as follows int x[ 5 ] = { 1, 2, 3, 4, 5 }; Suppose the address of x is 1000 and assuming that each integer requires two bytes, the five elements will be stored as follows Elements 

x[0]

x[1]

x[2]

x[3]

x[4]

Value



1

2

3

4

5

Address



1000

1002

1004

1006

1008

Base Address The name x is defined as a constant pointer pointing to the first element , x[0] and therefore the value of x is 1000, the location where x[0] is stored. That is x = &x[0] =1000. Pointers and Character Strings

char str[5]=”good”; the compiler automatically insets the null character ‘\0’ at the end of the string. C supports an alternative method to create strings using pointer variables of type char. char *str=”good”; This creates a string for the literal and then stores in the pointer variable str. The pointer str now points to the first character of the string “good” as g

o

str

o

d

UNIT-4.pdf

If return type is not explicitly specified, C will. assume that it is an integer type. If the function is not returning anything the return. type is void. Function_name ...

372KB Sizes 5 Downloads 393 Views

Recommend Documents

No documents