0% found this document useful (0 votes)
5 views

Module3 Chapter2

Module 3 chapter 2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Module3 Chapter2

Module 3 chapter 2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

MODULE 3

Functions
3.12 Introduction
 C enables its programmers to break up a program into segments commonly known as functions,
each of which can be written more or less independently of the others.
 Every function in the program is supposed to perform a well-defined task.
 Therefore, the program code of one function is completely insulated from the other functions.

Definition
 “The set of instructions that performs some specific, well-defined task is called as a Function.”
Or
 “Function is a small program or program segment that carryout some specific well-defined
tasks”.
 Fig. 1.9 explains how the main() function calls another function to perform a well-defined task.
 In the figure, we can see that main() calls a function named func1(). Therefore, main() is known as the
calling function and func1() is known as the called function.
 The moment the compiler encounters a function call, the control jumps to the statements that are a
part of the called function.
 After the called function is executed, the control is returned to the calling program.

3.12.1 Why are Functions Needed?


 Dividing the program into separate well-defined functions facilitates each function to be written
and tested separately. This simplifies the process of getting the total program to work.
 Understanding, coding, and testing multiple separate functions is easier than doing the same for one
big function.
 If a big program has to be developed without using any function other than main(), then there will be
countless lines in the main() function and maintaining that program will be a difficult task.
 All the libraries in C contain a set of functions, which have been pre-written and pre-tested, so
the programmers can use them without worrying about their code details. This speeds up
program development, by allowing the programmer to concentrate only on the code that he has to
write.

Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 1
 Like C libraries, programmers can also write their own functions and use them from different
points in the main program or any other program that needs its functionalities.
 When a big program is broken into comparatively smaller functions, then different programmers
working on that project can divide the workload by writing different functions.

3.13 Using Functions


While using functions, we will be using the following terminologies:
 A function f that uses another function g is known as the calling function, and g is known as the
called function.
 The inputs that a function takes are known as arguments.
 When a called function returns some result back to the calling function, it is said to return that
result.
 The calling function may or may not pass parameters to the called function. If the called function
accepts arguments, the calling function will pass parameters, else not.
 Function declaration is a declaration statement that identifies a function’s name, a list of
arguments that it accepts, and the type of data it returns.
 Function definition consists of a function header that identifies the function, followed by the body
of the function containing the executable code for that function.

3.14 Types of Functions


i. Library Functions/Pre-Defined/ Built-in Functions
 C Library of C Compiler has a collection of various functions which perform some standard and pre-
defined tasks.
 These functions written by designers of C Compilers are called as Library functions/Pre-Defined/Built-in
functions.
Ex: sqrt(n)- computes square root of n.
pow(x,y)- computes 𝑥 𝑦 .
printf()- used to print the data on the screen.
scanf()- used to read the data from the keyboard.
abs(x)- computes absolute value of x.

ii. User-Defined/ Programmer Defined Functions


 The functions written by the programmer/user to do the specific tasks is called User-Defined/ Programmer
Defined Functions.
 main( ) is the user defined function.

3.15 Elements of User-Defined Functions


 The three elements of user-defined functions are shown below:
i. Function Prototype/Declaration
ii. Function Definition
iii. Function Call

Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 2
3.15.1 Function Declaration/Function Prototype
 Before using a function, the compiler must know the number of parameters and the type of
parameters that the function expects to receive and the data type of value that it will return to the
calling program.
 Placing the function declaration statement prior to its use enables the compiler to make a check on
the arguments used while calling that function.
 The general format for declaring a function that accepts arguments and returns a value as result can be
given as:
return_data_type function_name(data_type variable1, data_type variable2,..);
Here, function_name is a valid name for the function. A function should have a meaningful name that
must specify the task that the function will perform.
return_data_type specifies the data type of the value that will be returned to the calling function as a
result of the processing performed by the called function.
(data_type variable1, data_type variable2, ...) is a list of variables of specified data types. These
variables are passed from the calling function to the called function. They are also known as arguments
or parameters that the called function accepts to perform its task.
Ex: int add(int a,int b);

 Things to remember about function declaration:


 After the declaration of every function, there should be a semicolon. If the semicolon is missing,
the compiler will generate an error message.
 The function declaration is global.
 Use of argument name in the function declaration is optional.
int func(int, char, floa t);
or
int func(int num, char ch, float fnum);
 A function cannot be declared within the body of another function.
 A function having void as its return type cannot return any value.
 A function having void as its parameter list cannot accept any value. So the function declared as
void print();
does not accept any input/arguments from the calling function .
 If the function declaration does not specify any return type, then by default, the function returns
an integer value. Therefore, when a function is declared as
sum(int a, int b);
Then the function sum accepts two integer values from the calling function and in sum returns an
integer value to the caller.
 Some compilers make it compulsory to declare the function before its usage while other compilers
make it optional.

3.15.2 Function Definition


 When a function is defined, space is allocated for that function in the memory.
 A function definition comprises of two parts:
 Function header
 Function body

Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 3
 The syntax of a function definition can be given as:
return_data_type function_name(data_type variable1, data_type variable2,..)
{
.............
statements
.............
return(variable);
}
 The number of arguments and the order of arguments in the function header must be the same as
that given in the function declaration statement.
 While return_data_type function_name(data_type variable1, data_type variable2,...) is known as
the function header, the rest of the portion comprising of program statements within the curly
brackets { } is the function body which contains the code to perform the specific task.
 Note that the function header is same as the function declaration. The only difference between the two
is that a function header is not followed by a semi-colon.
Ex: int add(int a,int b)
{
int sum;
sum=a+b;
return sum;
}

3.15.3 Function Call


 The function call statement invokes the function.
 When a function is invoked, the compiler jumps to the called function to execute the statements
that are a part of that function.
 Once the called function is executed, the program control passes back to the calling function. A
function call statement has the following syntax:
function_name(variable1, variable2, ...);
 The following points are to be noted while calling a function:
 Function name and the number and the type of arguments in the function call must be same
as that given in the function declaration and the function header of the function definition.
 Names (and not the types) of variables in function declaration, function call, and header of
function definition may vary.
 Arguments may be passed in the form of expressions to the called function. In such a case,
arguments are first evaluated and converted to the type of formal parameter and then the body
of the function gets executed.
 If the return type of the function is not void, then the value returned by the called function may
be assigned to some variable as given below.
variable_name = function_name(variable1, variable2, ...);
Ex: add(a,b);

Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 4
3.16 return STATEMENT
 The return statement terminates the execution of the called function and returns control to the
calling function.
 When the return statement is encountered, the program execution resumes in the calling function at
the point immediately following the function call.
 A return statement may or may not return a value to the calling function.
 The syntax of return state can be given as
return <expression>;
Here expression is placed in between angular brackets because specifying an expression is
optional.
 A function that has void return type cannot return any value to the calling function.

3.17 Passing Parameters to Functions


 There are two ways in which arguments or parameters can be passed to the called function.
Call by value: The values of the variables are passed by the calling function to the called function.
Call by reference The addresses of the variables are passed by the calling function to the called
function.

1. Call by Value
 In this method, the called function creates new variables to store the value of the arguments
passed to it. Therefore, the called function uses a copy of the actual arguments to perform its
intended task.
 If the called function is supposed to modify the value of the parameters passed to it, then the
change will be reflected only in the called function. In the calling function, no change will be
made to the value of the variables. This is because all the changes are made to the copy of the
variables and not to the actual variables.

Example: Write a C program to add two numbers using call by value.


#include<stdio.h>
int add (int a,int b)
{
int sum;
sum = a + b; Output:
return sum; Enter the values of a and b: 4 5
} result =9

void main()
{
int a,b, res;
printf(“Enter the values of a and b:”);
scanf(“%d%d”,&a,&b);
res = add(a,b);
printf(“result =%d\n”, res);
}

Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 5
 Following are the points to remember while passing arguments to a function using the call-by value
method:
 When arguments are passed by value, the called function creates new variables of the same
data type as the arguments passed to it.
 The values of the arguments passed by the calling function are copied into the newly created
variables.
 Values of the variables in the calling functions remain unaffected when the arguments are
passed using the call-by-value technique.

Pros and cons


 The biggest advantage of using the call-by-value technique is that arguments can be passed as
variables, literals, or expressions, while its main drawback is that copying data consumes
additional storage space.
 In addition, it can take a lot of time to copy, thereby resulting in performance penalty, especially if
the function is called many times.

2. Call by Reference
 When the calling function passes arguments to the called function using the call-by-value
method, the only way to return the modified value of the argument to the caller is explicitly
using the return statement. A better option is to pass arguments using the call-by-reference
technique.
 In this method, we declare the function parameters as references rather than normal variables.
 When this is done, any changes made by the function to the arguments it received are also
visible in the calling function.
 To indicate that an argument is passed using call by reference, an asterisk (*) is placed after the type
in the parameter list. Hence, in the call-by-reference method, a function receives an implicit
reference to the argument, rather than a copy of its value. Therefore, the function can modify the
value of the variable and that change will be reflected in the calling function as well.

Example:
1. Write a C program to add two numbers using call by reference.
#include<stdio.h>

int add (int *a,int *b)


{
int sum;
sum = *a + *b;
return sum;
}

void main()
{
Output:
int a,b, res;
printf(“Enter the values of a and b:”); Enter the values of a and b: 4 5
scanf(“%d%d”,&a,&b); result =9
res = add(&a,&b);
printf(“result =%d\n”, res);
}

Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 6
2. Write a C program to swap two numbers using call by reference.
#include<stdio.h>
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int a,b, res;
printf(“Enter the values of a and b:”); Enter the values of a and b: 10 20
scanf(“%d%d”,&a,&b); Before swapping: a=10 b=20
printf(“Before swapping: a=%d\tb=%d”, a, b); After swapping: a=20 b=10
swap(&a,&b);
printf(“After swapping: a=%d\tb=%d”, a, b)
}

Output:
Enter the values of a and b: 10 20
Before swapping: a=10 b=20
After swapping: a=20 b=10

Advantages
 Since arguments are not copied into the new variables, it provides greater time and space efficiency.
 The function can change the value of the argument and the change is reflected in the calling
function.
 A function can return only one value. In case we need to return multiple values, we can pass those
arguments by reference, so that the modified values are visible in the calling function.

Disadvantages
 However, the drawback of using this technique is that if inadvertent changes are caused to variables
in called function then these changes would be reflected in calling function as original values
would have been overwritten.

3.18 Scope of Variables


 In C, all constants and variables have a defined scope.
 By scope we mean the accessibility and visibility of the variables at different points in the
program.
 A variable or a constant in C has four types of scope: block, function, program, and file.

Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 7
3.18.1 Block Scope
 We have studied that a statement block is a group of statements enclosed within opening and
closing curly brackets { }.
 If a variable is declared within a statement block then as soon as the control exits that block, the
variable will cease to exist.
 Such a variable also known as a local variable is said to have a block scope.
 So far we had been using local variables.
 For example, if we declare an integer x inside a function, then that variable is unknown to the rest of
the program (i.e., outside that function).
 Variables declared with same names as those in outer block mask the outer block variables while
executing the inner block.
 In nested blocks, variables declared outside the inner blocks are accessible to the nested blocks,
provided these variables are not re-declared within the inner block.

3.18.2 Function Scope


 Function scope indicates that a variable is active and visible from the beginning to the end of a
function.
 In C, only the goto label has function scope.
 In other words function scope is applicable only with goto label names. This means that the
programmer cannot have the same label names inside a function.
Ex:
void main()
{


loop: /*A goto label has function scope */


goto loop /* the goto statement */


}
 In this example, the label loop is visible from the beginning to the end of the main () function.
Therefore, there should not be more than one label having the same name within the main()
function.

3.18.3 Program Scope


 Till now we have studied that variables declared within a function are local variables. These local
variables (also known as internal variables) are automatically created when they are declared in the
function and are usable only within that function. The local variables are unknown to other
functions in the program. Such variables cease to exist after the function in which they are declared
is exited and are re-created each time the function is called.
 However, if you want a function to access some variables which are not passed to it as arguments,
then declare those variables outside any function blocks. Such variables are commonly known as
global variables and can be accessed from any point in the program.

Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 8
Lifetime: Global variables are created at the beginning of program execution and remain in existence
throughout the period of execution of the program. These variables are known to all the functions in
the program and are accessible to them for usage. Global variables are not limited to a particular function
so they exist even when a function calls another function. These variables retain their value so that they
can be used from every function in the program.

Place of Declaration: The Global variables are declared outside all the functions including main(). It
is always recommended to declare them on top of the program code.

Name conflict: If we have a variable declared in a function that has same name as that of the global
variable, then the function will use the local variable declared within it and ignore the global variable.
Consider the following program,
#include <stdio.h >
int x = 10;
void print();

void main()
{
printf(“\n The value of x in the main() = %d”, x);
int x = 2;
printf(“\n The value of local variable x in the main() = %d", x);
print();
}

void print()
{
printf(“\n The value of x in the print() = %d”, x);
}
Output:
The value of x in the main() = 10
The value of local variable x in the main()= 2
The value of x in the print () = 10

3.18.4 File Scope


 When a global variable is accessible until the end of the file, the Variable is said to have file scope.
To allow a variable to have file scope, declare that variable with the static keyword before specifying
its data type:
static int x;
 A global static variable can be used anywhere from the file in which it is declared but it is not
accessible by any other file.

3.19 Storage Classes


 Storage class defines the scope (visibility) and lifetime of variables and/or functions declared
within a C program.
 In addition to this, the storage class gives the following information about the variable or the function.
 The storage class of a function or a variable determines the part of memory where storage space
will be allocated for that variable or function (whether the variable function will be stored in a
register or in RAM).

Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 9
 It specifies how long the storage allocation will continue to exist for that function or variable.
 It specifies the scope of the variable or function.
 It specifies whether the variable or function has internal, external, or no linkage.
 It specifies whether the variable will be automatically initialized to zero or to any
indeterminate value.
 C supports four storage classes: automatic, register, external, and static.
 The general syntax for specifying the storage class of a variable can be given as:
<storage_class_specifier> <data type > <variable name>

3.19.1 auto Storage Class


 The auto storage class specifier is used to explicitly declare a variable with automatic storage.
 It is the default storage class for variables declared inside a block.
 For example, if we write
auto int x;
then x is an integer that has automatic storage. It is deleted when the block in which x is declared is
exited.
 The auto storage doss can be used to declare variables in a block or the names of function
parameters.
 Important things to remember about the variables declared with auto storage class are as follows :
 All the variables declared within a function belong to automatic storage class by default.
 They should be declared at the start of the program block, right after the opening curly brackets
{.
 Memory for the variable is automatically allocated upon entry to a block and freed
automatically upon exit from that block.
 The scope of the variable is local to the block in which it is declared.
 Every time the block is entered, the variable is initialized with the values declared.
 The auto variables are stored in the primary memory of the computer.
 If auto variables are not initialized at the time of declaration, then they contain some garbage
value.

3.19.2 register Storage Class


 When a variable is declared using register as its storage class, it is stored in a CPU register instead of
RAM.
 Since the variable is stored in a register, the maximum size of the variable is equal to the register
size.
 A register variable is declared in the following manner:
register int x;
 Register variables are used when quick access to the variable is needed.
 Each time the block is entered, the register variables defined in that block are accessible and the
moment that block is exited, the variables become no longer accessible for use.

3.19.3 extern Storage Class


 The extern storage class is used to give a reference of a global variable that is visible to all the
program files.
 Such global variables are declared like any other variables in one of the program files. .
 To declare a variable x as extern write,
extern int x;

Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 10
 External variables may be declared outside any function source code file as any other variable is
declared.
 Usually external variables are declared and defined in the beginning of a source file.
 Memory is allocated for the external variables when the program begins execution and remains
allocated until the program terminates.
 In case if the external variable is not initialized, then it will be initialized to zero by default.
 External variables have global scope, i.e. these variables are visible and accessible from all the
functions in the program.

3.19.4 static Storage Class


 static is the default storage class for all global variables.
 Static variables have a lifetime over the entire program. i.e., memory for the static variables is
allocated when the program begins running and is freed when the program terminates.
 To declare an integer x as static, write
static int x = 10;
Here x is a local static variable.
 Static local variables when defined within a function are initialized at the runtime.
 The static variables are initialized just once, when defined within a function it is not re-initialized
when the function is called again and again.
 When a static variable is not explici1ly initialized by the programmer, then it is automa1ically
initialized to zero when memory is allocated for it

Comparison of Storage Classes

3.20 Recursion
 “The process in which a function calls itself again and again is called as Recursion”.
 A recursive function is defined as a function that calls itself to solve a smaller version of its task
until a final call is made which does not require a call to itself.

Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 11
 Since a recursive function repeatedly calls itself, it makes use of the system stack to temporarily store
the return address and local variables of the calling function. Every recursive solution has two major
cases. They are:
 Base case, in which the problem is simple enough to be solved directly without making any
further calls to the same function.
 Recursive case, in which first the problem at hand is divided into simpler sub-parts. Second the
function calls itself but with sub-parts of the problem obtained in the first step. Third, the result is
obtained by combining the solutions of simpler sub-parts.
Ex: To calculate n!, we multiply the number with factorial of the number that is 1 less than that number.
In other words, n! = n × (n–1)!

 Every recursive function must have a base case and a recursive case. For the factorial function,
 Base case is when n = 1, because if n = 1, the result will be 1 as 1! = 1.
 Recursive case of the factorial function will call itself but with a smaller value of n, this case can
be given as:
factorial(n) = n × factorial (n–1)

Example:
1. Write a C program to calculate factorial of a given number.
#include<stdio.h>
int factorial(int n)
{
if(n==1)
return 1;
else
return (n*fact(n-1));
}
Output:
void main()
{ Enter a number: 5
int n,fact; Factorial of given number =120
printf(“Enter a number:”);
scanf(“%d”,&n);
fact=factorial(n);
printf(“\nFactorial of given number=%d”,fact);
}

Greatest Common Divisor


The greatest common divisor of two numbers (integers) is the largest integer that divides both the
numbers. We can find the GCD of two numbers recursively by using the Euclid’s algorithm that states:

Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 12
2. Write a C program to calculate the GCD of two numbers using recursive functions.
#include <stdio.h>
int GCD(int x, int y)
{
int rem;
rem = x%y;
if(rem==0)
return y;
else
return (GCD(y, rem));
}

void main()
{
Output:
int x, y, res;
printf("\n Enter the two numbers: "); Enter the two numbers: 8 12
scanf("%d %d", &x, &y); GCD = 4
res = GCD(x, y);
printf("\n GCD = %d", x, y, res);
}

3. Write a C program to find the Fibonacci series using recursive function.


#include<stdio.h>
int fibonacci (int n)
{
if( n = = 0)
return 0;
else if (n = = 1)
return 1;
else
return ( fibonacci (n-1) * fibonacci (n-2));
}

Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 13
void main()
{ Output:
int n, i, res; Enter a value for n:
printf(“Enter a value for n:”);
5
scanf(“%d”,&n);
printf(“ The Fibonacci series is: \n”); The Fibonacci series is:
for ( i =0; i < n ; i ++) 0
{ 1
res = fibonacci(i); 1
printf(“%d\n”, res); 2
} 3
}

3.21 Function Parameters


 “The list of variables defined in the function header within the parenthesis are called Function
parameters”.
 There are 2 types of parameters in ‘C’ functions.
i. Actual parameters
ii. Formal parameters

i. Actual or Real Parameters


 The variables that are used when a function is invoked are called actual parameters.
 Actual parameters are used in the Calling function when a function is invoked.
 Actual parameters send values or addresses to the formal parameters. Formal parameters receive them and
use the same values.
 Actual parameters can be constants, variables or expressions.
Ex: res=add(m,n);

ii. Formal or Dummy Parameters


 The variables defined in the function header or function definition are called formal parameters.
 All the variables should be separately declared and each declaration must be separated by commas.
 The formal parameters receive values form the actual parameters.
 If the formal parameters receive the address from the actual parameters, then they should be declared as
pointers.
 The formal parameters should be only variables. Expressions and constants are not allowed.
Ex: int add(int a,int b);

Example Program: C Program to define actual and formal parameters.


#include<stdio.h>

int add(int a,int b) // Formal Parameters a, b


{
int sum;
sum=a+b;
return sum;
}

Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 14
void main()
{
int m,n,res;
printf(“Enter the values for m,n\n”);
scanf(“%d%d”,&m,&n);
res=add(m,n); // Actual parameters m,n
printf(“Sum=%d\n”,res);
}

Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere 15

inprotected.com

You might also like