Documente Academic
Documente Profesional
Documente Cultură
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
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:
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.
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.
#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()
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
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()
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 (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
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; }
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
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}
30 20 10
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.
Out put 0
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
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