Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

Notes For Bachelor of Science (TU)

BSC NOTES
PDF
COLLECTION
www.avashkattel.com.np/bscnotes
Unit 7: Functions (5 Hrs)

1
Contents of unit
• Library Functions, User Defined functions, function prototype,
function call, and function definition., function arguments and return
types, passing arrays to function, passing strings to functions,
function call by value, passing arguments by address, scope visibility
and lifetime of a variable, local and global variable

2
Function
• A function is defined as self-contained block of statements that performs a
particular specified job in a program.

• Actually, function is a logical unit composed of a number of statements


grouped together into a single unit.

• It often defined as a section of a program performing a specific job.

• A C program may include one or more functions.


• In fact, C program is collection of functions.

3
• Write a C program that finds factor of a positive number using function
• #include<stdio.h>
• #include<conio.h>
• void factorial();
• int main()
• {
• printf("Function\n");
• factorial();
• getch();
• return 0;
• }
• void factorial()
• {
• int n,f=1,i;
• printf("Enter any number\n");
• scanf("%d",&n);
• for(i=1;i<=n;i++)
• {
• f =f*i;
• }
• printf("Factoril of %d = %d",n,f);
• }

4
• Write C program that finds factorial of a number using function
• #include<stdio.h>
• int factorial(int n)
• {
• int f=1,i;
• for(i=1;i<=n;i++)
• {
• f = f*i;
• }

• return f;
• }
• int main()
• {
• int r,m;
• printf("Enter any number \n");
• scanf("%d",&m);
• r = factorial(m);
• printf("factorial = %d",r);
• }

5
Advantages of Function
• Manageability
• Code Reusability
• Redundancy Elimination
• Logical Clarity
• Easier Task Division

6
Advantages of Function
• Manageability : The use of function perform specific job in a program
makes easier to write small programs keep track of what they do.
• It makes programs significantly easier to understand and maintain by
breaking them up into easily manageable chunks
• The code for each job or activity is placed in individual function such
that testing and debugging becomes easy and efficient.

7
Advantages of Function
• Code Reusability: A single function can be used multiple times in a
single program from different places.
• It avoids re-writing the same code again and again such that it
reduces extra effort
• Thus, it helps to reuse the code once written and tested.
• The C standard library is an example of functions being reused.

8
Advantages of Function
• Redundancy Elimination: A function written is called many times in
the program when needed to perform the specified task.
• The particular job or activity is to be accessed repeatedly multiple
times from several different places within or outside the program is
written within function.
• If the function is not used in such a situations, the code for the same
activity is to be re-written every time.
• Thus, the use of function avoid the need of redundant programming
for the task.

9
Advantages of Function
• Logical Clarity : When a single program is decomposed into various
well-defined functions, the main program consists of a series of
function calls rather than countless lines of code so that the size of
main program seems small and program becomes logically clear to
understand.
• It helps to make program easier to write, understand, debug and test.

10
Advantages of Function
• Easier Task Division: The number of programmers working on one
large project can divide the workload on the basis of functions.
• Finally they can be integrated in the program

11
Types of functions
• There are two types of functions
• Library Functions
• User defined functions

12
Library Functions
• These are the functions which are already written, compiled and
placed in C library and they are not required to be written by a
programmer.
• We can use these functions as required by just calling them.
• For example, printf(), scanf(), sqrt().

13
User Defined Functions
• These are the functions which are defined by user at the time of writing a
program.
• The user has choice to choose name, return type, arguments type etc.
• for example , the function computing factorial of a positive number.
• Syntax:
• return_type function_name (argument list)
• {
• // function body
• }
• For example:
• int factorial(int n)
• {
• ……
• }
14
Components of a Function
• Function Definition
• Function Declaration or prototype
• Function Call
• Return Statement
• Function Parameter(Arguments)

15
Function Definition
• One or more statements that describes the specific task to be done
by a function is called function definition.
• It consists of function header, which defines function’s name, its
return type and its arguments list that a function body, which is block
of code enclosed in parentheses.
• Syntax:
• return_type function_name (arguments lists)
•{
• // function body
• }

16
Function Declaration or prototype

• The function declaration or prototype is model or blueprint of a function.


• If a function is used before it is defined in the program, then function
declaration or prototype is needed to provide the following information to
the compiler.
I. The name of the function
II. The type of the value returned by the function
III. The number and the type of arguments that must be supplied while
calling the function.
When a user-defined function is defined before its use, there is no need for
the function declaration. The syntax for the function declaration is:
return _type function_name (arguments list);

17
Return Statement
• The function defined with its return type must return a value of that type.
• For example, if a function has return type int, it returns an integer value
from the function to the calling program.
• The “return” is a keyword used at the end of every function body to return
the specific value form the function, is called return statement.
• If a function has void as return statement, there is not need of return
statement.
i. it immediately the control back to calling function
ii. It return value to calling function
• Syntax:
• return (expression)

18
Function Call
• A function is called by specifying its name, followed by a list of
arguments enclosed in parentheses and separated by commas.
• If function call does not require any arguments, an empty pair of
parentheses must follow the name of function.

19
Function Parameter(Arguments)

• Function parameters are the means for communication between the


calling and the called functions.
• They can be classified into formal parameters and actual parameters.
• The formal parameters are the parameters given in the function
declaration and function definition.
• The actual arguments or parameters are specified in the function call.

20
Category of user defined function
• Category 1: Function with no arguments and no return value
• Category 2: Function with arguments and no return value
• Category 3: Function with no arguments and with return value
• Category 4: Function with arguments and return value

21
Category 1: Function with no arguments and no return value

• When a function has no arguments, it does not receive any data from the
calling function.
• Similarly, when it does not return any value, the calling function does not
receive any data from the called function.
• Thus, in such type of functions, there is no data transfer between the
calling function and the called function.
• This type of function defined as:
• void function_name()
• {
• /*body of function*/
• }

22
Category 2: Function with arguments and no return value

• The function of this category has arguments and receives the data
from the calling function.
• The function completes the task and does not return any values to
the calling function.
• Such type of functions are defined as:
• void function_name(argument list)
•{
• /*body of function */
•}
23
Category 3: Function with no arguments and with return value

• The function of this category has no arguments and does not receive the
data from the calling function.
• After completing its task, it returns the result to the calling function
through return statement.
• Thus, there is data transfer between called function and calling function
using return value and arguments.
• These types of functions are defined as:
• return_type function_name()
• {
• /* body of function
• }

24
Category 4: Function with arguments and return value

• The function of this category has arguments and receives the data from the
calling function.
• After completing its task, it returns the result to the calling function
through return statement.
• Thus, there is data transfer between called function and calling function
using return value and arguments.
• These types of functions are defined as:
• return_type function_name(argument list)
• {
• /* body of function
• }

25
Different Types of Function Call
• The arguments in function can be passed in two ways:
• pass arguments by value and pass arguments by address or reference
or pointers.

26
Function call by value (or Pass arguments by value)

• When values of actual arguments are passed to a function as


arguments, it known as function call by value.
• In this type of call, the value of each actual arguments is copied into
corresponding formal argument of the function definition.
• The content of the arguments in the calling function are not altered,
even if they are changed in the calling function.
• The function is called using the syntax:
• function_name (value_of_argumnet1, value_of_argumnet2,,,,);

27
Function call by Reference (Pass Arguments by Address)

• In this type of function call, the address of a variable or argument is passed to a


function as argument instead of actual value of variable.
• A function can be called by passing address in its arguments as:
• function_name(address_of_argument1, address_of_arguments2,….);

28
Recursive Function
• A recursive function is one that calls to itself to solve a smaller version
of its task until a final call which does not require a self-call.

• Thus, a function is called recursive if it calls itself.

• The recursion in programming is a technique for defining a problem in


terms of one or more smaller versions of the same problem.
• The recursion is used for repeatitive computations in which each
action is stated in terms of previous results

29
Recursive Function
• To solve a problem using recursive function, the following two
conditions must be satisfied.
1. Problem could be written or defined in terms of its previous results
2. Problem statement must include a stopping conditions.

Mathematically, the factorial function can be defined

n! = 1 if n<=1
n*(n-1)! If n>1

30
• Write a C program that finds factorial of a number using recursive function
• #include<stdio.h>
• int fact(int n);
• int main()
• {
• int n;
• printf("Enter value of n\n");
• scanf("%d",&n);
• int f = fact(n);
• printf("The factorial of %d = %d\n",n,f);
• }
• int fact(int n)
• {
• if(n<=1)
• return 1;
• else
• return n*fact(n-1);
• }

31
• Write a C program to find nth Fibonacci number using recursive functions.
• #include<stdio.h>
• int fibo(int n);
• int main()
• {
• int n;
• printf("Enter value of n\n");
• scanf("%d",&n);
• printf("The %dth fibonacci number=%d",n,fibo(n));
• }
• int fibo(int n)
• {
• if(n<=1)
• return n;
• else
• return fibo(n-1)+fibo(n-2);
• }


32
• Write a c program to find product of two numbers using recursive functions
• #include<stdio.h>
• int product(int a,int b);
• int main()
• {
• int a=10,b=5;
• printf("The product=%d",product(a,b));
• }
• int product(int a,int b)
• {
• if(b==1)
• return a;
• else
• return a+product(a,b-1);
• }


33
• Write a C program that finds x^n using recursive function
• #include<stdio.h>
• int power(int a,int b);
• int main()
• {
• int x,n;
• printf("Enter value of x and n\n");
• scanf("%d%d",&x,&n);
• printf("%d^%d = %d\n",x,n,power(x,n));
• }
• int power(int x,int n)
• {
• if (n==0)
• return 1;
• else
• return x*power(x,n-1);
• }

34
• Write a C program that finds product of two numbers using recursive function
• #include<stdio.h>
• int product(int a,int b);
• int main()
• {
• int a,b;
• printf("Enter value of a and b\n");
• scanf("%d%d",&a,&b);
• printf("%d * %d = %d\n",a,b,product(a,b));
• }
• int product(int a,int b)
• {
• if (b==0||a==0)
• return 0;
• else if (a==1)
• return b;
• else
• return b+product(a-1,b);
• }
• 35
Passing Array to function
Like ordinary variables and values, it is possible to pass the value of an
array element or even entire array as an argument to a function.
To pass an entire array to a function, the array name must appear by
itself without subscripts.
The corresponding formal argument in the function definition is written
in the same manner although it must be declared as an array.

36
• // Passing array as function arguments
• #include<stdio.h>
• #define N 5
• void print(int a[]);
• int main()
• {
• int a[N] = {1,2,3,4,5};
• print(a); // array name
• }
• void print(int a[])
• {
• for(int i=0;i<N;i++)
• {
• printf("%d ",a[i]);
• }
• }

37
Overview of Local, Global, Static and Register variables

• Local Variables (Automatic): The automatic variables are always


declared within a function or block and are local to the particular
function or block in which they are declared.
• As local variables are defined within a body of the function, or block,
they are accessible from the same block only.
• The compiler shows errors in case other functions try to access the
variables
• The local variables are created when the function is called and
destroyed automatically when the function is existed.

38
Local Variable
• The default value of local variables is an unpredictable value which is called
garbage value.
• The scope of local variable is only within the block in which it is defined.
• Its life time is till the control remains within the block in which the variable
is defined.
• Note:
• Scope : The scope of can be defined as the region over which the variable is
visible or valid.
• Life Time: The period of time during which memory is associated with a
variable is called the life time or extent of the variable
39
• #include<stdio.h>
• void print();
• int main()
• {
• int a=10,b=5;
• printf("a=%d\n",a);
• printf("b= %d\n",b);
• print();
• }
• void print()
• {
• int a,b;
• a=1,b=2;
• printf("a=%d\n",a);
• printf("b= %d\n",b);
• }

• 40
Global Variables (External)
• Variables that are accessible, alive and active throughout the entire
program are known as external variables.
• They are also known as global variables.
• The global variables are declared outside any block or function.
• The default initial value of these variables is zero.
• The scope is global
• The life time is as long as the program’s execution does not come to
an end.

41
Example
• #include<stdio.h>
• int a=20;
• void fun()
• {
• int a=10;
• printf("In fun a=%d\n",a);
• }
• int main()
• {
• printf("In main a=%d\n",a);
• fun();
• }

42
Static Variables
• A static variable can only be accessed from the function in which it
was declared, like a local variable.
• The static variable is not destroyed on exit from the function; instead
its value is preserved and becomes available again when the function
is next time called.
• The static variables are declared as local variables, but the declaration
is preceded by the word static for example
• static int counter

43
Static Variables
• The static variables can be initialized as normal: the initialization is
performed only once, when the program starts up.

• The default initial value for this type of variable is zero.

• Its scope is local to the bock in which the variable is defined and its
life time is global. That is, its value persists between different function
calls).

44
Example
• #include<stdio.h>
• void print();
• int main()
• {
• for(int i=1;i<=10;i++)
• print();
• }
• void print()
• {
• static int a=1;
• printf("%d ",a);
• a = a+1;
• }

45
Register Variables
• Register variables are special case of automatic variables.
• Automatic variables are allocated storage in the memory of computer,
however, for most computers, accessing data in memory is
considerably slower than processing in the CPU.
• If store the variable in register it becomes faster.
• The register variables behave in every other way line automatic
variables.

46
Example
• #include<stdio.h>
• int main()
• {
• for(register int i=1;i<=10;i++)
• {
• printf("%d ",i);
• }
• }

47

You might also like