POP Module 3 Functions Notes
POP Module 3 Functions Notes
SRIDEVI G M
(Assistant Professor)
NOTES For
FUNCTIONS
1. Function Declaration/Function Prototype
Before using the function, the compiler must know about the number and type of parameters that the function
expects to receive and the datatype of the value that it will return to the calling function. Placing the function
declaration statement prior to its use enables the compiler to check on the arguments used while calling that function
return_data_type specifies the data type of the value that is returned to the calling function by the called function.
function_name is a valid identifier for the function. Every function must have a different name.
data_type variable1, data_type variable2,….. is a list of variables of specified data types. They are also known as
arguments or parameters. These values are passed by the calling function when a function call is made.
2. Function Definition
When a function is defined, memory is allocated for the function. A function definition contains 2 parts:
Function header and function body. Function body is enclosed within braces {} after the function header.
Syntax for function definition:
}
The function header is same as that in the function declaration but without the semicolon.
The number and order of arguments in the function header must be same as in the function declaration.
Example:
3. Function call
The function call invokes the function. When a function is called, the compiler jumps to the called function to
execute the body of the called function. After execution of all the statements, the program control passes back to the
calling function.
Format for function call: function_name (variable1, variable2,…..)
Program Output
PASSING PARAMETERS TO THE FUNCTION
There are two ways that a C function can be called from a program. They are,
1. Call by value
2. Call by reference
1. CALL BY VALUE:
In call by value method, the value of the variable is passed to the function as parameter.
The value of the actual parameter can not be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because, value of actual
parameter is copied to formal parameter.
Note:
2. CALL BY REFERENCE:
• In call by reference method, the address of the variable is passed to the function as parameter.
• The value of the actual parameter can be modified by formal parameter.
• Same memory is used for both actual and formal parameters since only address is used by both
parameters.
EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY REFERENCE):
• In this program, the address of the variables “m” and “n” are passed to the function “swap”.
• These values are not copied to formal parameters “a” and “b” in swap function.
• Because, they are just holding the address of those variables.
• This address is used to access and change the values of the variables.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);
int main()
{
int m = 22, n = 44;
// calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
}
COMPILE &
RUN
OUTPUT:
values before swap m = 22
and n = 44
values after swap m = 44
and n = 22
While calling a function, we pass values of variables While calling a function, instead of passing the
to it. Such functions are known as “Call By Values”. values of variables, we pass address of
variables(location of variables) to the function
known as “Call By References.
In this method, the value of each variable in calling In this method, the address of actual variables in
function is copied into corresponding dummy the calling function are copied into the dummy
variables of the called function. variables of the called function.
With this method, the changes made to the dummy With this method, using addresses we would have
variables in the called function have no effect on the an access to the actual variables and hence we
values of actual variables in the calling function. would be able to manipulate them.
In call by value, we cannot alter the values of actual In call by reference we can alter the values of
variables through function calls. variables through function calls.
Values of variables are passed by Simple technique. Pointer variables are necessary to define to store
the address values of variables.
SCOPE OF VARIABLES
scope of a variable is its lifetime in the program. This means that the scope of a variable
is the block of code in the entire program where the variable is declared, used, and can be
modified.
Scope Meaning
Scope of a Identifier starts at the beginning of the file and ends at the end of the
file. It refers to only those Identifiers that are declared outside of all functions.
File The Identifiers of File scope are visible all over the file Identifiers having file
Scope scope are global
Block Scope of a Identifier begins at opening of the block / ‘{‘ and ends at the end of the
Scope block / ‘}’. Identifiers with block scope are local to their block
Function
Prototype
Scope Identifiers declared in function prototype are visible within the prototype
Function scope begins at the opening of the function and ends with the closing of
Function it. Function scope is applicable to labels only. A label declared is used as a target
scope to goto statement and both goto and label statement must be in same function
File Scope: These variables are usually declared outside of all of the functions and blocks, at
the top of the program and can be accessed from any portion of the program. These are also
called the global scope variables as they can be globally accessed.
#include <stdio.h>
// Global variable
int global = 5;
OUTPUT:
Before change within main: 5
After change within main: 10
Block Scope: A Block is a set of statements enclosed within left and right braces i.e. ‘{‘
and ‘}’ respectively. Blocks may be nested in C(a block may contain other blocks inside
it). A variable declared inside a block is accessible in the block and all inner blocks of that
block, but not accessible outside the block. Basically these are local to the blocks in which
the variables are defined and are not accessible outside.
#include <stdio.h>
int main()
{
{
int x = 10, y = 20;
{
// The outer block contains declaration of x and y, so following statement is valid and prints 10 and 20
printf("x = %d, y = %d\n", x, y);
{
// y is declared again, so outer block y is not accessible in this block
int y = 40;
// Changes the outer block variable x to 11
x++;
// Changes this block's variable y to 41
y++;
printf("x = %d, y = %d\n", x, y);
}
Output
x = 10, y = 20
x = 11, y = 41
x = 11, y = 20
Function Prototype Scope: These variables range includes within the function
parameter list. The scope of the these variables begins right after the declaration in
the function prototype and runs to the end of the declarations list. These scopes don’t
include the function definition, but just the function prototype.
Example:
// C program to illustrate function prototype scope
#include <stdio.h>
// file scope
int num1;
// Function to subtract
int Sub(int num1, int num2)
{
return (num1-num2);
}
int main(void)
{
printf("%d\n", Sub(10,5));
return 0;
}
Output
5
Function Scope: A Function scope begins at the opening of the function and
ends with the closing of it. Function scope is applicable to labels only. A label
declared is used as a target to go to the statement and both goto and label
statement must be in the same function.
Example:
void func1()
{
{
// label in scope even though declared later
goto label_exec;
label_exec: printf(“HELLO”);;
}
void funct2()
{
Now various questions may arise with respect to the scope of access of variables:
What if the inner block itself has one variable with the same name?
If an inner block declares a variable with the same name as the variable declared by the outer
block, then the visibility of the outer block variable ends at the point of the declaration by
inner block.
What about functions and parameters passed to functions?
A function itself is a block. Parameters and other local variables of a function follow the
same block scope rules.
Can variables of the block be accessed in another subsequent block?
No, a variable declared in a block can only be accessed inside the block and all inner blocks
of this block.
For example, the following program produces a compiler error.
int main()
{
{
int x = 10;
}
{
// Error: x is not accessible here
printf("%d", x);
}
return 0;
}
Error:
prog.c: In function 'main':
prog.c:8:15: error: 'x' undeclared (first use in this function)
printf("%d", x); // Error: x is not accessible here
^
prog.c:8:15: note: each undeclared identifier is
reported only once for each function it appears in
Example:
// C program to illustrate scope of variables
#include<stdio.h>
int main()
{
// Initialization of local variables
int x = 1, y = 2, z = 3;
// changing z
int z = 100;
printf("x = %d, y = %f, z = %d\n",
x, y, z);
}
}
return 0;
}
Output
x = 1, y = 2, z = 3
x = 10, y = 20.000000, z = 3
x = 10, y = 20.000000, z = 100
Storage Classes
What is Storage Class in C?
A storage class represents the visibility and a location of a variable. It tells from
what part of code we can access a variable. A storage class in C is used to describe
the following things:
NOTE: A variable is not only associated with a data type, its value but also a
storage class.
The scope of an auto variable is limited with the particular block only. Once the control goes
out of the block, the access is destroyed. This means only the block in which the auto variable
is declared can access it.
A keyword auto is used to define an auto storage class. By default, an auto variable contains a
garbage value.
Example, auto int age;
The program below defines a function with has two local variables
int add(void) {
int a=13;
auto int b=48;
return a+b;}
We take another program which shows the scope level “visibility level” for auto
variables in each block code which are independently to each other:
#include <stdio.h>
int main( )
{
auto int j = 1;
{
auto int j= 2;
{
auto int j = 3;
printf ( " %d ", j);
}
printf ( "\t %d ",j);
}
printf( "%d\n", j);}
OUTPUT:
321
Keyword extern is used to declaring a global variable or function in another file to provide the
reference of variable or function which have been already defined in the original file.
The variables defined using an extern keyword are called as global variables. These variables
are accessible throughout the program. Notice that the extern variable cannot be initialized it
has already been defined in the original file.
Example, extern void display();
First File: main.c
#include <stdio.h>
extern i;
main() {
printf("value of the external integer is = %d\n", i);
return 0;}
Second File: original.c
#include <stdio.h>
i=48;
Result:
• Static local variable is a local variable that retains and stores its value between function
calls or block and remains visible only to the function or block in which it is defined.
• Static global variables are global variables visible only to the file in which it is
declared.
The lifespan of a static variable is in the entire program code. A variable which is declared or
initialized using static keyword always contains zero as a default value.
4. Register Storage Class in C
You can use the register storage class when you want to store local variables within functions
or blocks in CPU registers instead of RAM to have quick access to these variables. For
example, “counters” are a good candidate to be stored in the register.
Example: register int age;
The keyword register is used to declare a register storage class. The variables declared using
register storage class has lifespan throughout the program.
It is similar to the auto storage class. The variable is limited to the particular block. The only
difference is that the variables declared using register storage class are stored inside CPU
registers instead of a memory. Register has faster access than that of the main memory.
The variables declared using register storage class has no default value. These variables are
often declared at the beginning of a program.
int fact(int);
int main()
{
int x,n;
printf(" Enter the Number to Find Factorial :");
scanf("%d",&n);
x=fact(n);
printf(" Factorial of %d is %d",n,x);
return 0;
}
int fact(int n)
{
if(n==0)
return(1);
return(n*fact(n-1));
}
x = 5 * fact(5-1);
x = 5 * 4 * fact(4-1);
x = 5 * 4 * 3 * fact(3-1);
x = 5 * 4 * 3 * 2 * fact(2-1);
x = 5 * 4 * 3 * 2 * 1;
x = 120;
GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that
divides both of them. For example, GCD of 20 and 28 is 4 and GCD of 98 and 56 is 14.
If a and b are two numbers then the greatest common divisor of both the numbers is denoted by gcd(a, b). To find
the gcd of numbers, we need to list all the factors of the numbers and find the largest common factor.
Suppose, 4, 8 and 16 are three numbers. Then the factors of 4, 8 and 16 are:
4 → 1,2,4
8 → 1,2,4,8
16 → 1,2,4,8,16
Therefore, we can conclude that 4 is the highest common factor among all three numbers.
According to Euclid’s formula, gcd(a,b) is given as
#include <stdio.h>
int gcd(int a, int b);
int main() {
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, gcd(n1, n2));
return 0;
}
TYPES OF RECURSION
Direct, indirect, tail recursive, non-tail recursive, linear and tree recursion.
1. Direct Recursion:
A function is directly recursive if it explicitly calls itself.
Example:
int func(int n)
{
if(n==0)
return n;
return func(n-1);
}
2. Indirect recursion
int func1(int n)
{
if(n==0)
return n;
return func2(n);
}
int func2(int x)
{
return func1(x-1);
}
3. Tail Recursion
A recursive function is said to be tail recursive if no operations are pending to be performed
after the recursive function returns to the caller. The function given below is non-tail recursive
as there is still multiplication operation remaining to be done after the function returns.
int factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
A function is called the tree recursion, in which the function makes more than one call
to itself within the recursive function. Example is generation of Fibonacci series
Fibonacci series is a sequence of Integers that starts with 0 followed by 1, in this sequence the
first two terms i.e. 0 and 1 are fixed, and we get the successive terms by summing up their
previous last two terms. i.e, the series follows a pattern that each number is equal to the sum of
its preceding two numbers
where F is the Fibonacci function having base values F(0)=0 and F(1)=1
Sample Series:
Program:
#include <stdio.h>
int main()
{
int num;
printf("Enter the number of elements to be in the series : ");
scanf("%d", &num);
return 0;
}