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

POP Module 3 Functions Notes

The document discusses the scope of variables in C programming. It defines three types of scopes: file scope, block scope, and function scope. File scope variables are declared outside of functions and can be accessed from anywhere in the file. Block scope variables are local to the block they are declared in. Function scope applies to labels and the variable can only be accessed within the function. An example is given showing a global or file scope variable that can be accessed and modified within functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views

POP Module 3 Functions Notes

The document discusses the scope of variables in C programming. It defines three types of scopes: file scope, block scope, and function scope. File scope variables are declared outside of functions and can be accessed from anywhere in the file. Block scope variables are local to the block they are declared in. Function scope applies to labels and the variable can only be accessed within the function. An example is given showing a global or file scope variable that can be accessed and modified within functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Subject- INTRODUCTION TO C PROGRAMMING

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

Syntax for function declaration:


return_data_type function_name(data_type variable1, data_type variable2,…..);

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.

Example: int add(int a, int b);

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:

return_data_type function_name (data_type variable1, data_type variable2,…..) //Function header


{
.
.
Statements;
.
.
return (variable/value/expression);

}
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:

int add (int a, int b)


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

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:

Formal parameter – This is the argument which is used in function definition


EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY VALUE):
In this program, the values of the variables “m” and “n” are passed to the function “swap”.
These values are copied to formal parameters “a” and “b” in swap function and used.
#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 value
printf(" values before swap m = %d \nand n = %d", m, n);
swap(m, n);
}
void swap(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}
COMPILE &
RUN
OUTPUT:
values before swap m = 22
and n = 44
values after swap m = 44
and n = 22

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);
}

void swap(int *a, int *b)


{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf("\n values after swap a = %d \nand b = %d", *a, *b);
}

COMPILE &
RUN
OUTPUT:
values before swap m = 22
and n = 44
values after swap m = 44
and n = 22

Difference between Call by Value and Call by Reference


Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally
differentiated by the type of values passed to them as parameters.
The parameters passed to function are called actual parameters whereas the parameters received by function
are called formal parameters.
Call By Value: In this parameter passing method, values of actual parameters are copied to function’s formal
parameters and the two types of parameters are stored in different memory locations. So any changes made
inside functions are not reflected in actual parameters of caller.
Call by Reference: Both the actual and formal parameters refer to same locations, so any changes made inside
the function are actually reflected in actual parameters of caller.
CALL BY VALUE CALL BY REFERENCE

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.

// C program to illustrate the global scope

#include <stdio.h>

// Global variable
int global = 5;

// global variable accessed from


// within a function
void display()
{
printf("%d\n", global);
}
// main function
int main()
{
printf("Before change within main: ");
display();

// changing value of global


// variable from main function
printf("After change within main: ");
global = 10;
display();
}

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);
}

// This statement accesses only outer block's variables


printf("x = %d, y = %d\n", x, y);
}
}
return 0;
}

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>

// function prototype scope (not part of a function definition)


int Sub(int num1, int num2);

// 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”);;
}

// label ignores block scope


goto label_exec;
}

void funct2()
{

// throws error: as label is in func1() not funct2()


goto label_exec;
}

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;

printf("x = %d, y = %d, z = %d\n",


x, y, z);
{

// changing the variables x & y


int x = 10;
float y = 20;

printf("x = %d, y = %f, z = %d\n",


x, y, z);
{

// 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:

• The variable scope.


• The location where the variable will be stored.
• The initialized value of a variable.
• A lifetime of a variable.
• Who can access a variable?

Thus a storage class is used to represent the information about a variable.

NOTE: A variable is not only associated with a data type, its value but also a
storage class.

What are the Types of Storage Classes in C?


There are total four types of standard storage classes. The table below represents
the storage classes in C.

Storage class Purpose


auto It is a default storage class.
extern It is a global variable.

It is a local variable which is capable of returning a value even when


static
control is transferred to the function call.

register It is a variable which is stored inside a Register.

1. Auto Storage Class in C


The variables defined using auto storage class are called as local variables. Auto stands for
automatic storage class. A variable is in auto storage class by default if it is not explicitly
specified.

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

2. Extern Storage Class in C


Extern stands for external storage class. Extern storage class is used when we have global
functions or variables which are shared between two or more files.

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:

value of the external integer is = 48

3. Static Storage Class in C


The static variables are used within function/ file as local static variables. They can also be
used as a global variable

• 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.

Example: static int count = 10;


Keep in mind that static variable has a default initial value zero and is initialized only once in
its lifetime.

#include <stdio.h> /* function declaration */


void next(void);
static int counter = 7; /* global variable */
main()
{
while(counter<10)
{
next();
counter++;
}
return 0;
}
void next( void )
{ /* function definition */
static int iteration = 13; /* local static variable */
iteration ++;
printf("iteration=%d and counter= %d\n", iteration, counter);
}
Result:

iteration=14 and counter= 7


iteration=15 and counter= 8
iteration=16 and counter= 9
Global variables are accessible throughout the file whereas static variables are accessible only
to the particular part of a code.

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.

#include <stdio.h> /* function declaration */


main()
{
{
register int weight;
int *ptr=&weight ;/*it produces an error when the compilation occurs ,we cannot get a
memory location when dealing with CPU register*/
}
}
OUTPUT:

error: address of register variable 'weight' requested


The next table summarizes the principal features of each storage class which are
commonly used in C programming

Storage Default Initial


Declaration Storage Scope Lifetime
Class Value
Inside a Within the
auto Memory Unpredictable Within the function/block
function/block function/block
Inside a CPU Within the
register Garbage Within the function/block
function/block Registers function/block
Entire the file and other files
Outside all
extern Memory Zero where the variable is declared program runtime
functions
as extern
Static Inside a
Memory Zero Within the function/block program runtime
(local) function/block
Static Outside all
Memory Zero Global program runtime
(global) functions
#include<stdio.h>

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;

Finding GCD of two numbers using recursion

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;
}

int gcd(int a, int b) {


if (b != 0)
return gcd(b, a % b);
else
return n1;
}

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

A function is said to be indirectly recursive if it contains a call to another function which


ultimately calls it.

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));
}

Tail-recursive function for factorial can be written as


int factorial( int n, int fact )
{
if ( n==1 )
return fact;
else
factorial( n-1, n*fact ); //No pending multiplication operation
}

//main function to test above function


int main( ){
int n,value;

//input an integer number


printf( "Enter the number : " );
scanf( "%d", &n );

value = factorial( n,1 ); /* Function for factorial of number */


printf( "Factorial of %d = %d\n",n,value );
return 0;
}
4. Linear and tree recursion
A function is called linear recursive if the function makes a single call to itself at each time the
function runs and grows linearly in proportion to the size of the problem. Example is factorial
of a number.
Factorial function is called only once within the function.

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

Mathematically it can be written as : F(n)=F(n−1)+F(n−2)

where F is the Fibonacci function having base values F(0)=0 and F(1)=1
Sample Series:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...

Program:
#include <stdio.h>

// fibonacci() funtion definition


int fibonacci(int num)
{
if (num == 0)
{
return 0;
}
else if (num == 1)
{
return 1;
}
else
{
return fib (num - 1) + fib (num - 2); //Fibonacci function is called
twice
}
}

int main()
{
int num;
printf("Enter the number of elements to be in the series : ");
scanf("%d", &num);

for (int i = 0; i < num; i++)


{
printf("%d, ", fib (i));
}

return 0;
}

You might also like