Sunteți pe pagina 1din 53

Unit-IV

4.1 functions- function definition, arguments, return value, prototype, arguments and parameters. 4.2 parameters passing- call by value and call by reference, passing array as arguments to functions. 4.3 recursive functions- definition, examples, advantages and disadvantages. 4.4 macros- definition, examples, comparison with functions.

functions
All c programs have at least one function that is the main. When the program grows into larger, may have many disadvantages. 1. Difficult to write a larger programs 2. Difficult to identify the logical errors and correct. 3. Difficult to read and understand. 4. Larger programs prone for more errors.

A program is divided into a main module and its related modules. Each module is in turn divided into sub modules until the resulting modules are smaller; that is, until they are not further division. The process of subdividing a problem into manageable parts called top-down design.

If any module has sub modules that is called as calling module and sub modules are called called modules. one module is communicate with other module through calling module. A c program consists of one or more functions, one and only one of which must be named main. the function which is calling other function is called calling function. A function whom it called is called called function A called function receives control from the a calling function, when it completes its task, it returns control to the calling function. the main function called by the operating system, in turn main function calls the other function to do some task.

A large program divided into series of individual related programs called modules. These modules are called functions. Functions are classified into two categories 1. Library functions ( built-in functions). 2. User-defined functions

Library (built in) functions


C is a library it is a collection of various types of functions which perform some standard and predefined tasks. This are part of the c compiler that have been written for general purpose are called library functions. example printf() scanf() sqrt() Advantage 1.No need to write the code because the functions are already available so it makes the programmers job much easier. 2. these functions are used anywhere in the program.
User defined functions

The functions are written by the programmer to achieve some work Ex- add(); func1();

function
Definition. A function is a self- contained block of code that performs a particular task. It takes some data from the main program and may or may not returns a value.
A function name is used three times: for declaration/prototype, in a call, and for definition.

Function Syntax
Function Prototype:

Parameter names can be omitted from the function prototype

return_type function_name (type1 name1, type2 name2, ..., typen namen) ; Return type and parameter types must be provided in the prototype Semi-colon indicates that this is only the function prototype, and that its definition will be found - Function_name: any valid identifier - Return_type: data type of the result (default int) elsewhere
- void - function returns nothing - Returning control If nothing returned Note- declaration is not allowed return; inside of the main. or, until reaches right brace It must be declared outside the main If something returned return expression;

Return type- the type of value return by the called function to its calling function after its task finished off. Function _name- give name to the function as naming the variables. Argument list/parameters- contains the valid variable names separated by commas and must enclosed in parenthesis. Note:- while naming the function space is not allowed.

No semi-colon Function Definition

return_type function_name (type1 name1, type2 name2, ...,typen namen) { ....statements... } Body of the function appears in its definition Parameter names are required here theyll be used in the function body

Declarations and statements: function body (block) Function can not be defined inside another function

Points to remember
C program must have at least one function that must be main. C program can have any number of functions. if function is declared, it must be called by some other function. A function to be called when the function name is followed by a semicolon.
#include<stdio.h> void func1(); main()\\calling function { func1();\\ this function is called from main printf(we are in main\n); }//main void func1()\\ called funciton { printf(we are in func1\n); }//func1

When a function is followed by a pair of braces in which one or more statements may be included is called function definition.
void func1()\\ called funciton { printf(we are in func1\n); }//func1

Any function can be called from any other function. Even main can be called from other functions.
main() { func(); } func() { main(); }

A function can be called any number of times. function can also called itself is called recursion.

Each function is called in the sequence we have specified in the main function.

main() { printf(\n I am calling other functions); func1(); func2(); func3(); printf(all functions are called\n); Output: }//main func1() I am calling other function { in func1 printf(in func1\n); in func2 }//func1 in func3 func2() all functions are called. { printf(in func2\n); }//func2 After each function task is over func3() the control passed to the calling function(main()). { printf(in func1\n); }//func3

7 One function can also call the other function which has already
been called.
main() { printf(I am in main\n); func1(); printf(I back in main\n); }//main func1() { printf(in func1\n); func2(); printf(I back in func1\n); }//func1 func2() { printf(In func2\n); func3(); printf(I back in func2\n); }//func2 func3() { printf(in fac3\n); }//func3

a function cannot be defined inside the other function. main() { func1(); func2(); }//main func1() { printf(\nthis is func1); func2() { printf(\nthis is func2); }//func2() }//func1()

called function may or may not send information (data) back to the calling function. If called function return some value to the calling function at the end of the function definition (before }) use return statement.
void func1(); void main() { func1(); printf(\nhai); }//main void func1() { printf(hello); return; }//func1()

return; this statement says that does not return any value. This may or may not used in void functions. return(expression);- it return some value to the calling function. Note- a function return only single value.

Categories of functions
Functions may belong to one of the following categories. 1. functions with no arguments and no return value. 2. functions with no arguments and return value. 3. functions with arguments and no return value. 4. functions with arguments and return value.

1. functions with no arguments and no return value.


If the function has no arguments, it does not receive any arguments/ parameters from the calling function. It does not return any value to the calling function. In this case, return type must be specified as void and put empty parenthesis. #include<stdio.h>
#include<conio.h> void add(); void main() { add(); } void add() { int a,b,c; printf("enter the a and b values"); scanf("%d %d",&a,&b); c=a+b; printf("\nc=%d",c); return;}

2.functions with no arguments and return value.


In which called function does not receive in arguments from calling function. However, end of its task it return some value to the calling function. In this case, return value must be specified and parenthesis is #include<stdio.h> empty #include<conio.h>

#include<stdio.h> int add(); #include<conio.h> void main() int add(); { void main() int c; { clrscr(); clrscr(); printf("c=%d",c); printf("addition of two number=%d",add()); }//main }//main int add() int add() { { int a,b; int a,b; printf("\nenter a and b values"); printf("\nenter a and b values"); scanf("%d %d",&a,&b); scanf("%d %d",&a,&b); return(a+b); return(a+b); }//add() }//add()

3. functions with arguments and no return value.


Called function receives arguments from the calling function and called function doesnt return any value to calling function. In function prototype, we have to specifies no of arguments in the parenthesis and specify return type as void.
#include<stdio.h> #include<conio.h> void add(int,int); void main() { int a,b; clrscr(); printf("\nenter a and b values"); scanf("%d %d",&a,&b); a and b are add(a,b); actual arguments getch(); x and y are formal}//main arguments. void add(int x,int y) { int z; z=x+y; printf(z=%d",z); }

The arguments in the calling functions are called actual arguments. The arguments in the called function are called formal arguments. Actual and formal arguments need not be same

4. functions with arguments and return value.


#include<stdio.h> #include<conio.h> int add(int,int); void main() { int a,b,d; clrscr(); printf("\nenter a and b"); scanf("%d %d",&a,&b); d=add(a,b); printf("d=%d",d); getch(); }//main int add(int a,int b) { int c; c=a+b; return c; }//add() #include<stdio.h> #include<conio.h> int add(int,int); void main() { int a,b,c; clrscr(); printf("\nenter a and b"); scanf("%d %d",&a,&b); c=add(a,b); printf(c=%d",c); getch(); }//main int add(int a,int b) { return a+b; }//add() #include<stdio.h> #include<conio.h> int add(int,int); void main() { int a,b; clrscr(); printf("\nenter a and b"); scanf("%d %d",&a,&b); printf("%d",add(a,b)); getch(); }//main int add(int a,int b) { return a+b; }//add()

1.Function without arg and returntype #include<stdio.h> #include<conio.h> void add(); void main() { add(); } void add() { int a,b,c; printf("enter the a and b values"); scanf("%d %d",&a,&b); c=a+b; printf("\nc=%d",c); return;}

2.functions with no arguments and return value. #include<stdio.h> #include<conio.h> int add(); void main() { int c; clrscr(); printf("c=%d",c); }//main int add() { int a,b; printf("\nenter a and b values"); scanf("%d %d",&a,&b); return(a+b); }//add()

3. functions with arguments and no return value. #include<stdio.h> #include<conio.h> void add(int,int); void main() { int a,b; clrscr(); printf("\nenter a and b values"); scanf("%d %d",&a,&b); add(a,b); getch(); }//main void add(int x,int y) { int z; z=x+y; printf(z=%d",z); }

4. functions with arguments and return value. include<stdio.h> #include<conio.h> int add(int,int); void main() { int a,b,c; clrscr(); printf("\nenter a and b"); scanf("%d %d",&a,&b); c=add(a,b); printf(c=%d",c); getch(); }//main int add(int a,int b) { return a+b; }//add()

Differences between categories of functions.

Cycle-7
/*7.1 a function that takes an integer n as argumnet and return 1 if it is prime number and 0 otherwise*/ int prime(int n) #include<stdio.h> { #include<conio.h> int i,count=0; int prime(int); for(i=1;i<=n;i++) void main() { { if(n%i==0){ int n,c; count++; clrscr(); } printf("\n enter the n value"); }//for scanf("%d",&n); if(count==2) c=prime(n); { printf("%d",c); return 1; getch(); } }//main else { return 0; } }//prime

/*2.a function that takes a real number x and positive integer n as arguments and return xn*/ #include<stdio.h> #include<conio.h> #include<math.h> double power1(float,int); void main() { float x; int n; double result; clrscr(); printf("\n enter x in real and n in integer values"); scanf("%f %d",&x,&n); printf("result=%lf",power1(x,n)); getch(); }//main double power1(float x,int n) { return (pow(x,n)); }//power1

/*3. a function that takes a positive integer n as an argument and returns the nth fibonacci number*/ //function definition for fib #include<stdio.h> int fib(int n) #include<conio.h> { int fib(int); int a=0,b=1,i=3,fib; void main() while(i<=n) { { int n; fib=a+b; clrscr(); a=b; printf("\nenter the n value "); b=fib; scanf("%d",&n); i++; printf("%d fibonacci number is %d",n,fib(n)); }//while getch(); return fib; }//main }//fib()

Recursive functions
Definition- a function which calls itself is called recursion. Recursion is a repetitive process, where the function calls itself. Ex- factorial of a number

Iteration definition
fact (n) =1 =n*(n-1)*(n-2).3*2*1 Recursion definition if n=0 if n>0

fact (n) =1 if n=0 BASE CASE =n*fact (n-1) if n>0 GENERAL CASE

//factorial of a number using non recursive function. #include<stdio.h> #include<conio.h> int factorial(int); void main() { int number,fact; printf(enter the number); scanf(%d,&number); fact= factorial(number); getch(); }//main //definition of factrorial() factorial(int number) { int fact=1,x; for(x=1;x<=number;x++) { fact=fact*x; }//for return fact;

// factorial of a number using recursive function. #include<stdio.h> #include<conio.h> int factorial(int); void main() { int number,fact; printf(enter the number); scanf(%d,&number); fact= factorial(number); getch(); }//main // definition of factorial() factorial(int number) { int fact; if(number==0) return 1; else fact=number*factorial(number-1); return fact;

factorial(int number) number=4 { int fact; if(number==0) return 1; else fact=number*factorial(number-1); return fact; }//factorial()

Factorial(4) returns 24 to main because main is calling function to that.

factorial (4) =4*factorial (3)

factorial (4) =4*6=24

factorial (3) =3*factorial (2)

factorial (3) =3*2=6

factorial (2) =2*factorial (1)

factorial (2) =2*1=2

factorial (1) =1*factorial (0)

factorial (1) =1*1=1

factorial (0) =1

/* gcd of two numbers using recursion*/ #include<stdio.h> #include<conio.h> void main(){ int a,b,gcd; clrscr(); printf("\nEnter two numbers: "); scanf("%d %d",&a,&b); gcd=findgcd(a,b); printf("\nGCD of %d and %d is: %d",a,b,gcd); getch(); }// finding gcd int findgcd(int x,int y){ while(x!=y) { if(x>y) return findgcd(x-y,y); else return findgcd(x,y-x); }//while return x; }//findgcd

Passing parameters to a function


Parameters to be passed to a function in two ways. 1. call by value 2. call by reference. 1. call by value in which values of the actual arguments are copied into the corresponding formal arguments of the called function. whatever changes made in the formal arguments in the called function have no effect on the values of the actual arguments. 2. call by reference In this method the addresses of the actual arguments in the calling function are copied into the formal arguments of the called function. Whatever changes made in the formal arguments in the called function can have effect to the value of the actual arguments in the calling function.

Write a c program to swapping of two numbers using call by value and call by reference.
Call by value void swap(int,int); void main() { int a=10,b=20; swap(a,b); printf(\n a and b values after swapping); printf(\na=%d,b=%d,a,b); }//main // function definition swap(int x,int y) { int temp; temp=x; x=y; y=temp; printf(\nx=%d,y=%d,x,y); }//swap() Call by reference void swap(int,int); void main() { int a=10,b=20; swap(&a,&b); printf(\n and b values after swapping); printf(\n a=%d b=%d,a,b); }//main //function definition swap(int *x,int *y) { int temp; temp=*x; *x=*y; *y=temp; }//swap

Write a function to compute are and circumference of a circle, having area and circumference as pointer arguments and radius as an ordinary argument
void main() { int radius; float area,circum; printf(\n enter radius of a circle); scanf(%d,&radius); areacircum(radius, &area,&circum); printf(area=%f, area); printf(\n circumference=%f,circum); }//main areacircum(int r,float *a, float *c) { *a=3.14*r*r; *c=2*3.14*r; }

Passing arrays as arguments to functions


We can pass array elements as arguments to the called function in two ways 1. pass individual array element at a time. 2. pass the entire array at a time 1. passing individual array elements. we can pass individual array elements to the called functions by either call by value or call by reference. Call by reference Call by value void main() void main() { { int i; int i; int arr[]={10,20,30,40,50}; int arr[]={10,20,30,40,50}; for(i=0;i<5;i++) for(i=0;i<5;i++) display(&arr[i]); display(arr[i]); getch(); getch(); }//main }//main display( int *x) display( int x) { printf(%d,*x); { printf(%d,x); }//display }//display

2. pass the entire array at a time


Fixed length array- the size of the array is known when the program is written. int arr[10]; Variable length array- the size of the array is known when the program is run. int arr[n]; If u want to pass the fixed length array as argument to the called function, simply pass the array name to called function.
void display(int x[]); void main() { int arr[5]={10,20,30,40,50}; clrscr(); display(arr); getch(); }//main
void display(int x[]) { int i; for(i=0;i<5;i++) { printf(" %d",x[i]); }//for }//display()

In variable length array we have to pass array name as well as size of the array to the called function.
void display(int arr[],int size); void display(int arr[],int size) void main() { { int i; int a[10]; for(i=0;i<size;i++) int n,i; printf(" %d",arr[i]); clrscr(); } printf("\n enter the size of the array"); scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&a[i]); Note- In c, the name of an array gives the display(a,n); address of the first element in the array getch(); }//main

.
Advantages Using recursion, the length of the program can be reduced.

Disadvantages of recursion1. Recursion is difficult to understand 2. Recursive functions are slow and takes a lot of memory space compared to non recursive/ iterative functions. 3. If the programmer forgets to specify the exit condition in the
recursive function, the program will execute out of memory. In such a situation user has to press Ctrl+ break to pause and stop the function.

Storage classes in c
The storage class determines the part of member storage is allocated for an object and how long the storage allocation continues to exit. A scope specifies the part of the program which a variable name is visible, that is the accessibility of the variable by its name. Storage class tells us: 1) Where the variable is stored. 2) Initial value of the variable. 3) Scope of the variable. Scope specifies the part of the program which a variable is accessed. 4) Life of the variable. How long variable exist in the program. There are four types of storage classes: 1) Automatic storage class 2) Register storage class 3) Static storage class 4) External storage class

1.Automatic storage class


1.
2. 3.

4. 5. 6.

7.

the variable is declared with keyword auto. ( auto keyword is optional while declaring variables.) they must be declared at the start of a block. Memory is allocated automatically upon entry to a block and freed automatically upon exit from the block. Storage- automatic variable stored in the memory. Default initial value- garbage value. Scope- local to the block in which they are declared, including any blocks nested within that block. For this reasons automatic variable are also called local variable. Life within the block in which the variable is defined.
void main() { int x=10; { int x=20; { int x=30; printf(x=%d,x); } printf(x=%d,x); } printf(x=%d,x); Output}

Examples main() { auto int x; printf(%d,x); } Output gives garbage value.

30 20 10

2. Register storage class


1. Automatic variables are allocated storage in the main memory of the computer; however, for most computers, accessing data in memory is considerably slower than processing directly in the CPU. Registers are memory located within the CPU itself where data can be stored and accessed quickly. Normally, the compiler determines what data is to be stored in the registers of the CPU at what times. Thus, register variables provide a certain control over efficiency of program execution. Variables which are used repeatedly or whose access times are critical may be declared to be of storage class register. Variables can be declared with keyword register as register int x; Storage- variable stored in cpu registers rather than memory. Default initial value- garbage value. Scope- local to the block in which they are declared, including any blocks nested within that block. For this reasons automatic variable are also called local variable. Life within the block in which the variable is defined.

2.

3. 4.

5. 6. 7. 8.

9.

3.Static storage class


1. 2. 3. 4. 5. 6.
7. 8. 9.

Variables must be declared with the key word static. static int x; Storage- variable stored in computer memory. Default initial value- zero. Scope- local to the block in which they are declared. Life value of the variable persists between the different function calls. Static automatic variables continue to exist even after the block in which they are defined terminates. Thus, the value of a static variable in a function is retained between repeated function calls to the same function. In the case of recursive function calls we use static storage class. Static variables may be initialized in their declarations; however, the initializes must be constant expressions, and initialization is done only once at compile time when memory is allocated for the static variable. Static and auto variables are differ in their life and initial value.

Difference between static and auto


void main() { add(); add(); add(); getch(); }//main add() { auto int i=1; printf(%d,i); i++; }//add Out put 1 1 1 void main() { add(); add(); add(); getch(); }//main add() { static int i=1; printf(%d,i); i++; }//add Out put 1 2 3 void main() { static int i; printf(%d,i); }

Out put 0

4. External storage class


1. All variables we have seen so far have had limited scope (the block in which they are declared) and limited lifetimes (as for automatic variables). These variables are declared with keyword extern as extern int x; ( extern keyword may be omitted). Storage- Memory. Default initial value- zero. Scope- as long as the programs execution. Life- doesnt come to an end. External variables are declared outside the all the functions. So that they are available to all the functions in a program.

2.
3. 4. 5. 6. 7.

int i; void main() { printf(%d,i);->0 add();--------1 add();------2 sub();------1 sub();----0 }//main() add() { i++; printf(i=%di); }//add() Sub() { i--; printf(i=%d,i); }//sub()

extern int x=100; void main() { int x=200; printf(x=%d,x); display(); }// display() { print(%d,x); } Note- local variable has highest preference than global variable so that local variable value gets printed.

int x=20; void main() { extern int y; printf(%d %d,x,y); } int y=20;

- If any variable declared out side of the main is treated as extern variable/ global variable. -If any variable declared as global variable inside of the main that must be declared with key word extern and defined outside of the main.

Macros
Preprocessor- it is a program that processes our source program before it is passed to the compiler.
C source code (HAI.C)

preprocessor
Expanded source code (HAI.I)

compiler
Object code((HAI.obj)

Linker
Executable code (HAI.exe)

If a statement starts with symbol # those are called preprocessor commands. These are processed by the preprocessor before the compilation. Several preprocessor commands 1. macro expansion. 2. file inclusion. 3. conditional compilation. 4. miscellaneous directives.

Macro expansion
#define macro_name macro_value

Macros are start with #define directive. Space in between the # and define is optional. Space is necessary in between #define, macro_name and macro_value. Macro never terminated by a semicolon. It is customary to use capital letters for macro_names. How macros are processed? These statements must be preprocessed by the preprocessor during this, preprocessor replaces every occurrence of macro_name with the macro_value.

Example using macros #include<stdio.h> #include<conio.h> #define PI 3.14 3.14*radius*radius; void main() { float area,radius=3.0; area= PI*radius*radius; printf(%f,area); getch(); Use of Macro}//main suppose a constant value like 10 appears many #include<stdio.h> times in the program. This value may be changed #include<conio.h> to 8 sometimes. #define SIZE 10 you need to go through the program and manually void main() change each occurrence of the constant. { However, if you have defined constant value with int a[SIZE]; #define directive, you need to make one change in int i; the #define directive. for(i=0;i<SIZE;i++) scanf(%d,&a[i]); }//main

#define directive can also be used to define operators #include<stdio.h> #define LESS < void main() { #define directive can be used to int a=10,b=20; replace the entire c statement if(a LESS b) #define X printf(a is largest element); printf(a less than b); #define Y printf( a is smallest element); else #define LARGE a>b printf( b less than a); }//main void main()

#define directive can used to replace a condition or expression #define LARGE a>b void main() { int a=20,b=10; if(LARGE) printf(a is largest element); else printf(a is smallest element); getch(); }//main

{ int a=20,b=10; if(LARGE) X else Y getch(); }//main

Macros with arguments


Macros can have arguments just as functions can
#define AREA(x) (3.14*x*x) #define CIRCUM(x) (2*3.14*x) void main() { float r=3.0; float area,cir; area=AREA(r); cir=CIRCUM(r); printf(%f %f:,area,cir); getch(); }//main

Note- when we use macros with arguments macro_value must be put it in the parenthesis

// write the macros for sum of the squares of two numbers #include<stdio.h> #include<conio.h> #define SUMSQUARE(a,b) (a*a+b*b) void main() { int a,b; clrscr(); printf("enter two value"); scanf("%d %d",&a,&b); printf("\n sum of the squares of two numbers=%ld",SUMSQUARE(a,b)); getch(); }//main

Compare macros with functions


In a macro call the preprocessor replaces macro_name with macro_value. Whereas, in a function call the control is passed to a called function along with some arguments, some calculations are performed in the function and may return some value to the calling function. Macros make the program run faster but increase the program size, whereas functions make the program smaller and compact. If we use a macro hundred times in the program, the macro_value goes into our source code at hundred different places, thus increasing the program size. On the other hand, if a function is used, if it is called from hundred different places in the program, it would take the same amount of space in the program. So if you want to reduce the space use the function If you want make the program faster use macros.

S-ar putea să vă placă și