0% found this document useful (0 votes)
13 views41 pages

Function

This document discusses the concept of functions in C programming, explaining their structure, types, and usage. It covers predefined library functions and user-defined functions, detailing their declarations, definitions, and the importance of function prototypes. Additionally, it outlines the return statement, types of user-defined functions based on arguments and return types, and the advantages of using functions in programming.

Uploaded by

nabraj0102
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views41 pages

Function

This document discusses the concept of functions in C programming, explaining their structure, types, and usage. It covers predefined library functions and user-defined functions, detailing their declarations, definitions, and the importance of function prototypes. Additionally, it outlines the return statement, types of user-defined functions based on arguments and return types, and the advantages of using functions in programming.

Uploaded by

nabraj0102
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER 7

Function

prepared by: Er. Shiva pd. Mahato


Function
 A function is a self contained block of statements that performs a coherent or well
defined task.
 Every c program consists of one or more function. One of these functions must be
called main function.
 Execution of program will always begin by carrying out the instructions in main. Using
a function is something like hiring a person to do a job for you.
 The complex problem may be decomposed in to small or easily manageable parts.
Each small module is called function or specific module.
 C language supports two types of function I) Library Function or predefined function
ii) User defined function.
 Library Function:
 The library functions are predefined set of functions. Their task is limited.
 A user cannot understand the internal working of these functions.
 We can only use these functions for specific purpose for it is designed but we can’t
change or modify them. For example: sqrt(), pow(), getch() etc.

prepared by: Er. Shiva pd. Mahato


Function
User defined function:
 The function defined by the user according to his /her requirements is called as user
defined functions. The user can modify the function and understand the internal
working of the function. The user has full scope to implement his/her own ideas in the
function.
 Terminology used in function:
 To understand the basic concept of function in C language, we must be familiar with the
following terms:
 Function declaration or function prototype
 Function definition or called function (function decelerator and function body) or calee
 Passing arguments
 Function call or calling function
 Actual argument
 Formal Argument
 Return statement
 Return Value

prepared by: Er. Shiva pd. Mahato


Function
Function prototype or function declaration:
 When we use built in functions. The prototype of these function are given in the
respective header file.
 While defining user defined functions it must be necessary to declare its prototype.
Function prototype is actually the function header which is specified the existence of
function in the program before a function call is made.
 The function prototype provides a way of function declaration before they are used.
 The process of providing function prototype is called prototype declaration or function
declaration.
 The function prototype can be written as:
return_type function_name( list_of_argument);
e.g. int sum(int a, int b);
 A function prototype declaration consists of the function’s return type, function name
and arguments list terminated by semicolon.
 The function prototype is similar to the function header but it is terminated by the
semicolon.
 The name of argument in list_of_argument is optional but the type of argument should
be provided each separating by comma.

prepared by: Er. Shiva pd. Mahato


Function
 So, the above function prototype can also be declared as int sum (int, int);
Function prototype helps the compiler to check the number arguments that
the function takes their data type and type of value being returned by the
function
 When the programmer defines the function, the definition of the function
must be same like the declaration of the function. If the function definition is
done before the function main() then function prototype is not necessary. In
many ANSI standard C programming book, function prototype is not given but
function definition is written above the main() function .
 A function declaration provides the following information to the compiler:
 The name of the function
 The type of the value to be returned(optional,defaut returntype is integer)
 The number of arguments that must be supplied in a call to the function.
 The type of arguments that must be supplied in a call to the function.
When a function call is encountered, the compiler checks the function call with
its declaration so that correct argument types are used.

prepared by: Er. Shiva pd. Mahato


Function
Function definition or called function or callee:
 The function definition has two principle components: function decelerator (or
function header) and function body.
 Function decelerator( the first line of function definition): in function decelerator,
we must use the same function name, number of arguments, arguments types and
the return type same as in the function declaration but it does not have semicolon at
the end.
 Function body: Function decelerator is followed by the function body. It is
composed of statements that make up the function, delimited by braces which
define the actions to be taken by the function. The function definition has the
following form:
 return_type function_name( list_of_argument)
 {
//body

 }

prepared by: Er. Shiva pd. Mahato


Function
 Where return_type refers to a type returned by the function after operation is done. For
the function not returning any value, its return type is void.
 Function_name is the name of the function that is being defined which is any valid
identifier name like variables name.
 The list_of_argument specifies the list of variable and their types. The list_of_ argument
of called function is also called the formal parameters.
 The example given below is the function definition
 int sum(int a, int b)
 {
 int c;
 c=a+b;
 return(c);
 }
 The function definition consists two part function header and function body. The first
line of the function definition is called the function header and everything within the
braces is called the function body.
 The function body consists of declaration and group of statements. If a function returns
any value, the returning is done by writing a keyword return followed by a value to be
returned. A function may or may not return values
prepared by: Er. Shiva pd. Mahato
Function
 Actual argument: The arguments of the calling function are called actual argument.
 Formal argument: The arguments of called function are called formal argument.
 Arguments or parameter list: The argument list means means variables name enclosed
within the parenthesis and separated by comma.
 Function call: A compiler executes the actual code of the function definition when a
function name followed by semicolon (;) is encountered, it is an inactive part of the program
which comes in to life when a call is made to the function.
 Syntax for function call is:
function_name(list_of_argument);
 Here function_name is any valid identifier name and argument list is a comma separated list
of variable which are also called actual argument of the function. The return type is not
mentioned in the function call but returned value can be directly displayed or assigned to
another variable. For example, let us consider
 int a=3,b=5,c,d;
 c=sum(a,b);
 The statement c=sum(a,b); invokes the function sum()with two integer argument a and b.
The sum () return s the sum of argument a and b. the returned value is assigned to variable c.
 The number, type and order of arguments in the function declaration, function call and
function decelerator must be the same.

prepared by: Er. Shiva pd. Mahato


Function
 The return statement: The user defined function use return statement to return
the value to the calling function, from the called function to the calling function is
done by use of return statement.
 The result obtained by the function is sent back to the calling function through
the return statement.
 Even though, it is possible to pass to the called function any number of arguments
but the called function can only return one value per call.
 The return statement may or may not include an expression. Some examples are
 return;
 return c;
 return(a+b);
 return i++;
 When return statement without expression is encountered, execution of the
function is terminated and control is returned back to the calling function.
 If the return statement contains an expression, then the value of the expression is
returned back to the calling function.

prepared by: Er. Shiva pd. Mahato


Function
 If we have to terminate the function anywhere, we use return statement with a
value for function that returns a value and only return statement without a value
for function that does not return a value and terminate at that position.

 For a function that returns no value it is not necessary to have return at the end of
the function body.
 If there is no return statement, then control is passed back to the calling function
when the closing braces of the body encountered.

 Return value: This is outcome of the function. The result obtained by the
function is sent back to the calling function through the return statement.

 The return statement returns one value per call. The value returned is collected by
variable of the calling function.

prepared by: Er. Shiva pd. Mahato


Function
Different categories of User defined function:
 Depending upon whether arguments are present or not and whether a value is returned
or not, user defined functions are categories as follows:
 There are four types of user defined functions:
 Functions with no return type and no arguments
 Function with no return type and with arguments
 Function with return type and no arguments
 Function with return type and with arguments
 Functions with no return type and no arguments:
 The syntax to declare the function with no return type and no arguments is:
 void sum(); /*function prototype */

 void main()
 {
 sum(); /* calling function*/
 }

 void sum() /* called function or function definition*/
 {

 }

prepared by: Er. Shiva pd. Mahato


Function
 Neither data is not passed through the calling function nor is the data sent back from the
called function.
 There is not data transfer between calling and called function
 The function is only executed and nothing is obtained.
 If such function is used to perform any operation, they act independently. They read data
values and print in the same block.
 #include<stdio.h>
 void sum(); /*function prototype */
 void main()
 {
 sum(); /* calling function */
 }
 void sum() /*function definition*/
 { int a,b,c;
 printf(“enter a and b”);
 scanf(“%d”,&a,&b);
 c=a+b;
 printf(“\n the sum is %d”,c);
 }


prepared by: Er. Shiva pd. Mahato
Function
Function with no return type and with arguments:
 The syntax to declare the function with no return type and with arguments is:
 void sum( list of arguments); /*function prototype */

 void main()
 {
 sum(argument); /* calling function*/
 }

 void sum(argument) /* called function */
 {
 //body
 }
 Arguments are passed through calling function. The called function operates
on values. But no result is sent back.
 Such functions are partly dependent on the calling function.

prepared by: Er. Shiva pd. Mahato


Function

 #include<stdio.h>
 void sum(int a, int b); /*function prototype */
 void main()
 { int a,b;
 printf(“enter a and b”);
 scanf(“%d”,&a,&b);
 sum(a,b); /* calling function */
 }
 void sum(int x,int y)
 { int c;
 c=x+y;
 printf(“\n the sum is %d”,y);
 }

prepared by: Er. Shiva pd. Mahato


Function

Function with return type and no arguments:


 The syntax to declare the function with return type and with no arguments is:
 int sum(); /*function prototype */
 void main()
 {
 int y=sum(a,b); /* calling function */
 }
 int sum()
 {
 return( value);
 }
 In this type of function no argument are passed through the main function but
the called function return values.
 The called function is independent. It reads values from the keyboard or
generated from initialization and return value.
 Here both calling and called function are partly communicated with each
other.

prepared by: Er. Shiva pd. Mahato


Function
 #include<stdio.h>
 int sum(); /*function prototype */
 void main()
 { int y;
 printf(“enter a and b”);
 scanf(“%d”,&a,&b);
 y=sum(a,b); /* calling function */
 printf(“\n the sum is %d”,y);
 }
 int sum()
 { int a,b,c;
 printf(“enter a and b”);
 scanf(“%d”,&a,&b);
 c=x+y;
 return(c);
 }

prepared by: Er. Shiva pd. Mahato


Function

 Function with return type and with arguments:


 The syntax to declare the function with return type and with arguments is:
 int sum(list_of_argument); /*function prototype */

 void main()
 {
 int y=sum(list_of_argument); /* calling function */
 }
 int sum(list_of_argument)
 {
 return( value);
 }
 Arguments are passed through calling function. The called function operates
on values and result is sent back to called function.
 Here both calling and called function are communicated with each other.

prepared by: Er. Shiva pd. Mahato


Function

 #include<stdio.h>
 int sum(int a, int b); /*function prototype */
 void main()
 { int y;
 printf(“enter a and b”);
 scanf(“%d”,&a,&b);
 y=sum(a,b); /* calling function */
 printf(“\n the sum is %d”,y);
 }
 int sum(int x,int y)
 { int c;
 c=x+y;
 return(c);
 }

prepared by: Er. Shiva pd. Mahato


Function

Why use functions:


 Writing functions avoids rewriting the same code over and over.
 Using function it becomes easier to write program and keep tack of
what they are doing.
 Advantages of using function:
 Functions are easier to understand & maintain than lengthy programs.
 Functions can be tested independently and incrementally integrated
before the entire program has been written.
 Functions can be written independently by different programmers.
 Modules can be relatively independent, making debugging easier.
 Functions can be modified or replaced in order to tune a program to
the needs of specific applications without affecting the entire program.
 Code repetitions can be avoided.
 The overall program is simplified and easier to read.

prepared by: Er. Shiva pd. Mahato


Function

Storage class and scope of the variable:


 Every identifier in C has a storage class that provides information about its
visibility, lifetime and location.
 The period of time during which memory which a memory is associated with a
variable is characterized by storage classes.
 The storage class of a variable indicates the allocation of space to the variable
by the compiler.
 When we declare a variable, it is available only to specific part or block of the
program.
 The area or block of the c program from where the variable can be accessed is
known as the scope of the variable.
 The area or scope of the variable depends upon on its storage class i.e. where
and how it is declared.
 Any variable declared in c can have one of the four storage classes:
 Automatic variables or local variables
 External variable or global variables
 Static variables
 Register variables
prepared by: Er. Shiva pd. Mahato
Function

 Automatic variables or local variables:


 The variable declared inside a particular area or block is called automatic or
local variable.
 The variable declared inside the function without storage class name, by
default is an auto variable.
 Automatic variable are given only temporary space. The keyword for automatic
variable is auto. The feature of automatic variable is:
 Storage-Memory
 Default initial value- An unpredictable value, which is often called a garbage
value.
 Scope- Local to the block in which the variable is defined.
 Lifetime- Till the control remains within the block in which the variable is
defined.
 The general syntax to declare automatic variable is:
 Storage_class datatype variablename;
 auto int n;

prepared by: Er. Shiva pd. Mahato


Function

External variable or global variables:


 The variable which is active and alive through out the program is called
External variable or global variable.
 External variable are declared outside the main and can be accessed for entire
program.
 External variables are also called global variable. The keyword for external
variable is extern. The features of an external variable are:
 Storage-Memory
 Default initial value- zero
 Scope- global
 Lifetime- Till the program execution takes place.
 If both external and auto variable are declared with same name, in a program
first priority is given to the auto variable.
 The general syntax to declare automatic variable is:
 Storage_class datatype variablename;
 extern int n;

prepared by: Er. Shiva pd. Mahato


Function
 Example:
 # include<stdio.h>
 int a;
 void f1();
 void f2();
 void f3();
 void main()
 { int i;
 printf(“enter the value of a”);
 scanf(“%d”,&a);
 f1();
 f2();
 f3();
 }
 void f1()
 { printf(“\n in function f1 %d”,a+1);
 }
 void f1()
 { printf(“\n in function f12%d”,a+1);
 }
 void f1()
 { printf(“\n in function f3 %d”,a+1);
 }
prepared by: Er. Shiva pd. Mahato
Function
 Static variables:
 The static variable may be of an internal or external type depending upon the
where it is declared.
 In static storage class, storage is allocated at the beginning of the block
execution and it remains allocated until the programs execution terminates.
 The contents stored in these variables constant throughout the program
execution.
 The value of the variables persists between different function calls. Using this
property of static variable we can count how many times a function calls.
 The features of a static variable are:
 Storage-Memory
 Default initial value- zero
 Scope- may be local or global depending upon where it is declared.
 Lifetime- Till the program execution takes place.
 The general syntax to declare static variable is:
 Storage_class datatype variablename;
 static int n;

prepared by: Er. Shiva pd. Mahato


Function
 #include<stdio.h>
 #include<conio.h>
 #include<process.h>
 void main()
 { clrscr();
 for(; ;)
 print();
 getch();
 }
 void print()
 { static int m=0;
 printf(“\n m=”,m);
 m=m+1;
 if(m==3)
 exit(0);
 }
 Output:
 m=0
 m=1
 m=2
 m=3
 In this example, m is static integer so, each time when control is transfer between calling and called
function the incremented value of m is preserved.
prepared by: Er. Shiva pd. Mahato
Function
 Register variables:
 The storage class register tell the compiler that the associated variables should be store in
high speed memory register.
 When variable is declared with register storage class it allocates the required space in
CPU register instead of memory.
 The keyword register tells the compiler that the variable list followed by it is kept on the
CPU register. Since register access is faster than the memory access.
 The features of a static variable are:
 Storage-CPU Register
 Default initial value- An unpredictable value, which is often called a garbage value.
 Scope- local to the block where it is declared.
 Lifetime- Till the control remain within that block
 CPU register are limited in that case variables are assumed as auto and stored in memory.
We cannot use register class for all types of variables. The CPU registers in
microprocessor are 16 bit registers.
 The types float and double needs space of more than 16 bits but if we define, no errors
will show because compiler treated them auto class.

prepared by: Er. Shiva pd. Mahato


Function
 #include<stdio.h>
 #include<conio.h>
 #include<process.h>
 void main()
 { clrscr();
 for(; ;)
 print();
 getch();
 }
 void print()
 { static int m=0;
 printf(“\n m=”,m);
 m=m+1;
 if(m==3)
 exit(0);
 }
 Output:
 m=0
 m=1
 m=2
 m=3
 In this example, m is static integer so, each time when control is transfer between calling and called
function the incremented value of m is preserved.
prepared by: Er. Shiva pd. Mahato
Function
 Passing arguments (or parameter) to a function:
 There are two ways in which we can pass arguments to a function:
 Call by value
 Call by reference
 Call by value:
 Whenever a portion of the program is calling a function with a formal argument, the
control will be transferred form the main to the called function and the value of the
actual arguments is copied in to the formal arguments of function.
 When the control is transferred back from the called function to calling portion of the
program, the altered values are not transferred back. This type of passing arguments to a
function is known as call by value.
 Actual arguments are passed to the formal arguments and operation is done on the
formal arguments.
 Any change made in the formal argument does not affect the actual arguments because
formal arguments are photocopy of actual arguments.
 Change made in the formal arguments are local to the block to the called function
 Example:

prepared by: Er. Shiva pd. Mahato


Function
Example:
 #include<stdio.h>
 #include<conio.h>
 void modify(int a);
 void main()
 { int a=2;
 clrscr();
 printf(“\n a=%d before calling the function”,a);
 modify(a);
 printf(“\n a=%d after calling the function”,a);
 getch();
 }
 void modify( int p)
 { int m;
 m=p * p;
 }

prepared by: Er. Shiva pd. Mahato


Function
Call by reference:
 When a function is called by a portion of the program, the actual argument and the
values altered within the function will be returned to the calling portion of the program
in the altered form. This is technically known as call by reference or call by address.
 Instead of passing values, address reference are passed to the function. Function operates
on address rather than values.
 Any change that is made to the data item will be recognized in both the function and
calling portion program and changes made in the argument are permanent.
 #include<stdio.h>
 #include<conio.h>
 void modify(int *a);
 void main()
 { int a=2l;
 clrscr();
 printf(“\n a=%d before calling the function”,a);
 modify(&a);
 printf(“\n a=%d after calling the function”,a);
 getch();
 }


prepared by: Er. Shiva pd. Mahato
Function
 void modify( int *p)
 { int m;
 m=*p * *p;
 }
Recursive Function:
 The function which calls itself directly or indirectly again and again is known as the
recursive function.
 The recursive function calls itself until the given condition is satisfied. The function
definition where a statement within a body of the function calls itself is called recursion.
 Recursion is an elegant programming technique, but not the best way to solve the
problem.
To solve any problem recursively, two conditions must be satisfied
 i. The program must be written in recursive form.
 ii. The problem statement must include stopping condition.
 There is much difference between the normal function and the recursive function. The
normal function will be called by the main function whenever the function name is used.
 On the other hand, the recursive function will be called by itself directly or indirectly as
long as the given condition is satisfied.

prepared by: Er. Shiva pd. Mahato


Function
Advantages:
 Recursive code is more compact and often much easier to write and understand than the
non recursive equivalent.
 Recursion is especially convenient for recursively defined data structure like trees, link
list, stack, queue etc.
 Disadvantage:
 It consumes more storage space because the recursive calls along with automatic
variables are stored on the stack memory.
 The computer may run out of memory if recursive calls are not checked.
 Recursion is not more efficient in terms of memory if recursive calls are not checked.
 Recursion doesn’t offer any concrete advantage over non recursive procedures.

prepared by: Er. Shiva pd. Mahato


Function
 Example:
 Write a program to find the factorial of a number using recursive function.
 #include<stdio.h>
 float fact( int n);
 void main()
 {
 int n,z;
 printf(“enter the value of n”);
 scanf(“%d”,&n);
 z=fact(n);
 printf(“the factorial of a no is %d”,z);
 }
 int fact( int x)
 {
 if(x==0)
 return 1;
 else
 return (x*fact(x-1));
 }

prepared by: Er. Shiva pd. Mahato
Function
 Suppose we input the value of n as 5. When function is called as fact (5). The actual
argument is copied to formal argument x. i. e. the value of x is 5. Since the problem is
recursive in nature so, factorial is calculated as
 5! =5*4!
 =5*4*3!
 =5*4*3*2!
 =5*4*3*2*1!
 =5*4*3*2*1
 =120
 Now the value 120 is returned to the calling portion of the main program

prepared by: Er. Shiva pd. Mahato


Function
 Write a program to find xy using recursive function where x is f loat and y are
unsigned integers.
 #include<stdio.h>
 float calpow( float x,unsigned int y);
 void main()
 { unsigned int y;
 float x,z;
 printf(“enter the value of x and y”);
 scanf(“%f%u”,&x,&y);
 z=calpow(x,y);
 printf(“the x raised to the power is %f”,z);
 }

 float calpow(float x,unsingned int n)
 {
 if(n==0)
 return 1;
 else
 return (x*calpow(n-1));
 }

prepared by: Er. Shiva pd. Mahato


Function
 Example: The greatest common divisior(Highest common factor);
 #include<stdio.h>
 int gcdhcf(int,int);
 void main()
 { int a,b,gcd;

 printf(“enter the value of xaand b”);
 scanf(“%d%d”,&a,&b);
 gcd=gcdhcf(a,b);
 printf(“the greatest common divisor is %d”,gcd);
 }

 int gcdhcf(int x, int y)
 {
 if(y!=0)
 return gcdhcf(y,x%y);
 else
 return (x);
 }

prepared by: Er. Shiva pd. Mahato


Function
 The Fibonacci series
 The Fibonacci series is F(n)= F(n-1)+F(n-2), where F(0)=1 and F(1)=1. The Fibonacci series
of numbers in which each number is the sum of the previous two numbers. The first and
second Fibonacci numbers are 0 and 1.
 #include<stdio.h>
 #include<conio.h>
 void fibunaccii(int i, int j, int k);
 void main()
 { int n,i=0,j=1;
 printf("enter the number");
 scanf("%d",&n);
 printf("%d\t%d\t",i,j);
 fibunaccii(i,j,n-2);
 getch();
 }

prepared by: Er. Shiva pd. Mahato


Function
 void fibunaccii(int i, int j, int n)
 {
 static int k;
 if(n==0)
 return;
 else
 {k=i+j;
 printf("%d\t",k);
 i=j;
 j=k;
 fibunaccii(i,j,n-1);
 }
 }

prepared by: Er. Shiva pd. Mahato


Function
Write a program that takes an integer number and display whether it is prime or not using
recursive function.
 #include<conio.h>
 #include<stdio.h>
 int prime(int ,int );
 main()
 { int s,n;
 clrscr();
 printf("enter any five digit number");
 scanf("%d",&n);
 s=prime(n,n/2);
 if(s==1)
 printf(" the number is prime");
 else
 printf("the number is not prime");
 getch();
 }
 int prime(int n,int i)
 {
 if(i==1)
 return(1);
prepared by: Er. Shiva pd. Mahato
Function
 int prime(int n,int i)
 {
 if(i==1)
 return(1);
 else if (n%i==0)
 return 0;
 else
 return(prime(n,i-1));
 }

prepared by: Er. Shiva pd. Mahato


Function
 Example:
 Write a program to find the sum of numbers till the user enters non-negative integer’s
numbers using a recursive function.
 #include<stdio.h>
 int sumrecursively( );
 void main()
 {
 printf(“ sum=%d”,sumrecursively());
 }

 void sumrecursively()
 { int n;
 printf(“enter a number n”)’
 scanf(“%d”,&n);
 if(n<0)
 return 1;
 else
 return(n+sumrecursively());
 }
 Output:

prepared by: Er. Shiva pd. Mahato

You might also like