0% found this document useful (0 votes)
19 views51 pages

Programming in C Module 4

This document provides an overview of functions in C programming, detailing their definitions, types, advantages, and elements. It explains the distinction between built-in and user-defined functions, the importance of function declarations and definitions, and the role of parameters. Additionally, it categorizes functions based on their arguments and return values, and includes several code examples demonstrating function usage.

Uploaded by

ammakrishnab
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)
19 views51 pages

Programming in C Module 4

This document provides an overview of functions in C programming, detailing their definitions, types, advantages, and elements. It explains the distinction between built-in and user-defined functions, the importance of function declarations and definitions, and the role of parameters. Additionally, it categorizes functions based on their arguments and return values, and includes several code examples demonstrating function usage.

Uploaded by

ammakrishnab
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

Programming in C (1BEIT105)

MODULE 4
FUNCTIONS (CHAPTER 1)
1. INTRODUCTION
A function is a block of code that performs a specific task. A program can be broken into
segments commonly known as functions, each of which can be written more or less
independently of the others.

From the figure we can see that main() calls a function named func1(). Calling function is
main() and called function is func1(). Once a compiler encounters a function call, the control
jumps to the statements that are part of the called function. After the execution of called
function, the control is returned back to the calling function.
[Link] is function?
A function can be defined as a subprogram that also contains a group of statements to
do specific task.
1.1.1. Advantages of writing user defined functions

1. Reduction in the size of main( ).

2. Reusability of the written functions.

3. Program maintenance, testing and debugging is easier.

4. Functions can be shared among many C files.

5. Programmers can create their own functions library like header files.

6. Modular programming approach.

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 1


Programming in C (1BEIT105)
[Link] of Functions:

In C language, functions are classified into following two types.

1. Built-in functions: The functions designed and developed by C developers are called
built in or pre-defined functions.

Examples: scanf(), printf(), getch(), pow(),sqrt(),malloc(), strlen(), strcpy(), etc.

2. User defined function: The functions written by programmers are called user defined
functions.

Examples: isprime(n), fact(n), strcopy(str1,str2), sort(a,n), sum(n1,n2), etc.

1.3 Why are Functions needed?

 Dividing a program into separate well-defined functions facilitates each function to be


written and tested separately. The following figure shows that the main() function calls

other function for diving the entire code into smaller sections. This is known as top-
down approach.
 Understanding, coding and testing multiple separate functions is far easier than doing
it for one big program.
 Without functions, main() functions would consist of countless lines of code.
 C provides pre-written and pre tested functions which programmers can use which
speed sup the development process.
 When a big program is broken into functions, different programmers working on that
project can divide the workload by writing different functions.
 Like C libraries, programmers can also write their functions and use the mat different
points in the same program or different program.

2. Elements of user defined functions:

In order to design and develop user defined functions , the programmer needs to establish and use the
following elements of user defined functions.

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 2


Programming in C (1BEIT105)
Calling Function and Called Function: A function f that uses another function is knows as calling
function and is known as called function.

Arguments/Parameters: The input that a function takes is known as arguments or parameters.

Function Declaration: It is declaration statement that identifies a function with its name, a list of
arguments that it accepts, and the type of data it returns.

Function Definition: It consist of a function header that identifies the function, followed by the
body of the function containing the executable code for that function

2.1 FUNCTION DECLARATION/FUNCTION PROTOTYPE

Before using a function, the compiler must know about the number of parameters and
the type of parameters that the function expects to receive and the data type of the value that it
will return to the calling function. Placing the function declaration statement before it use
enables the compiler to check on the arguments used while calling that function.

General format for declaring the function is:

return_data_type function_name(data_Typevariable1, data_typevariable2,…..);

return_data_type specifies the data type of the value that will be returned to the
callingfunction.

function_name is a valid name for the function.

data_Type variable1, data_type variable2… is a list of variable of specified data types


that are passed from the calling function to the called function.

Example: float avg(int a, int b); This function calculates the average of two integer
rnumbers a and b and return a floating point value.

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 3


Programming in C (1BEIT105)
2.2 FUNCTION DEFINITON
When a function is defined, space is allocated for that function in the memory. A
function definition consists of 2parts: Function Header and Function body
return_data_type function_name(data_Type variable1,data_type variable2,…..)
{
local definitions;
Statements;
…….
return(value);
}

The number of arguments and order of arguments in the function header must be same as that
given in the function declaration statement. First line is the function header and statements
within{} is the function body which contains the code to perform a task. The list of the variables
in the function header is known as formal parameter list. The parameter list may have zero or
more number of parameters.
Example:
float avg( int a, int b)
{
float average;
average=(a+b)/2;
return(average);
}
intsum(intx,inty) /*functiondefinition*/
{
return(x+y);
}

2.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. Syntax of function call is as
follows:

function_name(variable1,variable2,….);

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 4


Programming in C (1BEIT105)
List of variables used in function call is knows as actual parameter list. When the function
declaration is present before the function call, the compiler can check if the correct number and
type of arguments are used in the function call.

Example: average=avg(10,20);

Program1: Write a program to add two integers using functions

#include<stdio.h>
int sum(int a, int b); /* function declaration
void main()
{
int a,b,c;
printf(“enter the values of a andb:”);
scanf(“%d%d”,&a,&b);
c=sum(a,b); /* function call
printf(“sum=%d”,c);
getch();

int sum(inta,intb)/*functiondefinition
{
int result;
result=a+b;
return(result);
}

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 5


Programming in C (1BEIT105)

/* to find square and cube of number by using functions*/


#include<stdio.h>
int square(int);/* function
declaration*/
int cube(int);
void main()
{
int n,ans1,an2;
clrscr();
printf("\n Enter a number");
scanf("%d",&n); o/p:
Enteranumber:2Square
ans1=square(n);/*functioncall*/ is 4
Cubeis8
ans2=cube(n);/* function call*/
printf("\n Square is %d",ans1);
printf("\n Cube is %d",ans2);
getch();
}

intsquare(intx) /*functiondefinition*/
{
return(x*x);
}
intcube(intx) /*functiondefinition*/
{
return(x*x*x);
}

/* to find factorial n by using function*/


#include<stdio.h>

long int fact(int x); /* function declaration*/


void main()
{

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 6


Programming in C (1BEIT105)
int n; o/p:
Enteranumber:4
long int ans; Factorial is 24

clrscr();
printf("\n Enter a number");
scanf("%ld",&n);
ans=fact(n);/*function call*/
printf("\n Factorial is%ld",ans);
getch();
}
longintfact(intx) /*functiondefinition*/
{
long int prod=1; int i;
for(i=1;i<=x;i++)
{
prod=prod*i;
}
return(prod);
}

/* to check for prime number by using


function*/
#include<stdio.h>
int isprime(int x);/* function
declaration*/
void main()
{
int n,r; o/p:
Enteranumber:17
clrscr(); 17isprimenumber

o/p:
printf("\n Enter a number"); Enteranumber:24
24isnotprimenumber
scanf("%d",&n);
r=isprime(n);/* function call*/
if(r==1)
printf("\n %d is prime
number",n);
[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 7
Programming in C (1BEIT105)
else
printf("\n %d is not prime number",n);
getch();
}
intisprime(intx)/*functiondefinition*/
{
int i;
for(i=2;i<=x/2;i++)
{
if(x%i==0)
return 0;
}
return(1);
}

/* to copy string1 into string2 by using user defined function*/

#include<stdio.h>
void STRCOPY(char str1[],char str2[]);/* function
declaration*/
void main()
{
char str1[50],str2[50];
clrscr();
printf("\n Enter string1 to be copy: ");
gets(str1);
STRCOPY(str1,str2);/* function call*/
getch();
}
void STRCOPY(charstr1[],charstr2[]) /*functiondefinition*/
{
int i;
o/p:
Enterastring1 to becopy:Happy
for(i=0;str1[i]!='\0';i++) Stringcopied…
String1=Happy String2=Happy
{

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 8


Programming in C (1BEIT105)
str2[i]=str1[i];
}
str2[i]='\0';
printf("\nStringcopied...");
printf("\nstring1=%sstring2=%s",str1,str2);
}
WriteaCprogramtosorttheelementsbypassingarrayasfunctionargument.(08marks)
#include<stdio.h>
void sort(int a[], int
x);
int main()
{
int a[25],i,n;
printf(“Enter number of elements”);
scanf(“%d”,&n);
printf(“\n Enter %delements”,n);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
sort(a,n);
return(0);
}

void sort(int a[],int x)


{
int i,j,temp;
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if[aj]>a[j+1])
{
temp=a[j];
[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 9
Programming in C (1BEIT105)
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf(“\n After Sorting \n”);
for(i=0;i<n;i++)
{
printf(“\n%d”,a[i]);
}

2.4 return STATEMENT


It terminates the execution of the called function and returns the control to the calling
function. A return statement may or may not return a value to the calling function. Syntax is as
follows:
return<expression>;

expression is optional, if present, it is converted to the type returned by the function. A


function that has void as its return type cannot return any value to the calling function.
For the functions that has no return statement, the control automatically returns to the
calling function after the last statement of the called function is executed.

A function may have more than one returnstatement.


#include<stdio.h>
int check_relation(int a, int b);
void main()
{
inta=3,b=5,res;
res=check_relation(a,b);
if(res==0)
printf(“EQUAL”);

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 10


Programming in C (1BEIT105)
if(res==1)
printf(“aisgreaterthanb”);
if(res==-1)
printf(“aislessthanb”);
getch();
return0;
}
int check_relation(int a,intb);
{
if(a==b)
return 0;
elseif(a>b)
return1;
else
return-1;
}
Output: a is less than b

3. Actual and Formal Parameters

The inputs, whichever we pass to functions to do specific task are called parameters or
arguments.

1. Actual parameters

2. Formal parameters

3.1 Actual Parameters:

The parameters passed during the function call in the main() function are called actual
parameters. These are actual (original) input data passed to user define function to do specific
task. i.e. the contents of actual parameters will be copied to formal parameters of a function.

3.2 Formal Parameters:

The parameters used in the function header of function definition are called formal
parameters. These parameters receive input data for processing from the actual parameters

from the calling function main(). i,e. formal parameters receive data from actual parameters.

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 11


Programming in C (1BEIT105)
The changes made to formal parameters do not affect the contents of actual parameters.

Examples:

/* Example for actual parameters */

#include<stdio.h>

void test(int x,int y);

void main()

int x=7,y=3;

clrscr();

printf("\n Before calling function: Actual parameters ");

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

test(x,y); /* Here, x & y are actual parameters*/

printf("\n After calling function: Actual parameters ");

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

getch();

void test(int x,int y) /* Here, x & y are formal parameters*/

x++;

y++;

printf("\n Inside function: Formal parameters");

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

o/p:

Before calling function: Actual parameters

x=7y=3

Inside function: Formal parameters

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 12


Programming in C (1BEIT105)

x=8y=4

After calling function: Actual parameters

x=7y=3

4. Categories of Functions based on number of arguments and return value:

The functions can be categorized into following 4 types based on the number of parameters or
inputs they receive to do specific task and return value.

i. Functions with no arguments and no return value

ii. Functions with arguments and no return value

iii. Functions with arguments and return value

iv. Functions with no arguments and return value

4.1 Functions with no arguments and no return value:

These functions do not receive any inputs from the calling function main() and do not return

any value back to it. But, these functions do specific task. i.e. there is no data transmission

between calling and called function.

#include<stdio.h>

void sum(void);

void main()

clrscr();

sum();

getch();

void sum(void)

int n1,n2,ans;

printf("\nEnter two numbers:");

scanf("%d%d",&n1,&n2);

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 13


Programming in C (1BEIT105)
ans=n1+n2;

printf("\nAddition is %d",ans);

4.2 Functions with arguments and no return value:

These functions receive inputs from the calling function main() to do specific task; but, do

not return any value back to it. The processed data will be displayed by it.

Example:

#include<stdio.h>

void sum(int x,int y);

void main()

int n1,n2;

clrscr();

printf("\nEnter two numbers:");

scanf("%d%d",&n1,&n2);

sum(n1,n2);

getch();

void sum(int x,int y)

int ans;

ans=x+y;

printf("\nAddition is %d",ans);

o/p:

Enter any two numbers:

73

Addition is 10

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 14


Programming in C (1BEIT105)
o/p:

Enter any two numbers:

73

Addition is 10

4.3 Functions with arguments and return value:

These functions receive inputs from the calling function main() to process and return a value

back to it. i.e. data transmission takes place between calling and called function.

Example:

#include<stdio.h>

int sum(int x, int y);

void main()

int n1,n2,ans;

clrscr();

printf("\n Enter any two numbers");

scanf("%d%d",&n1,&n2);

ans=sum(n1,n2);

printf("\n Addition is %d",ans);

getch();

int sum(int x, int y)

return (x+y);

4.4 Functions with no arguments and return value:

These functions do not receive any inputs from the calling function main(); but, return a value

back to it.

Example:

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 15


Programming in C (1BEIT105)
#include<stdio.h>

int sum(void);

void main()

int ans;

clrscr();

ans=sum();

printf("\nAddition is %d",ans);

getch();

int sum(void)

int n1,n2;

printf("\nEnter two numbers:");

scanf("%d%d",&n1,&n2);

return(n1+n2);

5. PASSING PARAMETERS TO FUNCTIONS


When a function is called, the calling function may have to pass some values to the called
function. There are 2 ways in which arguments or parameters can be passed to the called
function. They are:
 Call by Value – values of variables are passed by the calling function to the called
function.
 Call by Reference address of variables are passed by the calling function to the called
function.
5.1 CALL BY VALUE
In this method, the called function creates new variables to the store the value of the
arguments passed to it. Therefore, the called function uses a copy of the actual arguments to
perform the task. If the values are changed, then the change will be reflected only in the
called function. No changes will be made to the variable of the calling function.

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 16


Programming in C (1BEIT105)
Example:
#include<stdio.h>
void add(int n);
void main()
{
int num=2;
printf(“value before calling function=%d”,num);
add(num);
printf(“valueaftercalling function=%d”,num);
}
void add(int n);
{
n=n+10;
printf(“value of num in called function=%d”,num);
}

Output:
Value before calling function = 2
Value of num in called function=12
Value after calling function=2

Since the called function uses a copy of num, the value of num in the calling function
remains same.
Example:
#include<stdio.h>
void add(int n);
void main()
{
int num=2;
printf(“valuebeforecallingfunction=%d”,num);
num=add(num);

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 17


Programming in C (1BEIT105)
printf(“valueaftercalling function=%d”,num);
}
void add(int n);
{
n=n+10;
printf(“valueofnumincalledfunction=%d”,num);
return n;
}
Output:
Value before calling function=2
Value of num in called function=12
Value after calling function=12
Here, the changed value is retuned to the calling function.

5.2 CALL BY REFERENCE


In call by reference technique, the function n parameters are declared as references
rather than normal variables. When this is done any changes made by the called function to
the argument sit receives are visible in the calling function also. To indicate the call by
reference, an asterisk(*) is placed after the type in the parameter list.

Example:
#include<stdio.h>
void add(int *n);
void main()
{
int num=2;
printf(“valuebeforecallingfunction=%d”,num);
add(&num);
printf(“valueaftercalling function=%d”,num);
}
void add(int *n);
{
*n=*n+10;

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 18


Programming in C (1BEIT105)
printf(“valueofnumincalledfunction=%d”,num);
}

Output:
Value before calling function=2
Value of num in called function=12
Value after calling function=12

Advantages:
 Since arguments are not copied into new variables, it provides greater time and space
efficient.

 The called function can change the value of the argument and the change is reflected
in the calling function.
 A return statement can return only one value. In case we need multiple return values,
pass those arguments by reference.

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 19


Programming in C (1BEIT105)

Sl. Call by value Call by reference


No.
1 In this method, the values will be passed In this method, the addresses of actual
from actual to formal parameters. parameters will be passed to formal
Parameters.
2 The changes made to formal parameters The changes made to formal parameters
will not affect actual parameters. will affect actual parameters.
3 Capable to return only one value back to Capable to return multiple values back
called function. to called function.
4 Program execution is slower in Program execution is faster in
comparison with call by reference. comparison with call by value.
5 Pointers knowledge is not required Pointers knowledge is required.
6 Example: Example:
int sum(int x, int y) void swap(int *x, int *y)
{ {
return(x+y); int temp;
} temp=*x;
*x=*y;
*y=temp;
}

6. SCOPE OF VARIABLES
In C, all constants and variables have a defined scope. Scope means accessibility and
visibility of the variables at different points in the program. A variable or a constant in C has 4
types of scope:
1. Block Scope
2. Function Scope
3. Program Scope
4. File Scope
6.1 BLOCK SCOPE
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

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 20


Programming in C (1BEIT105)
have a block scope. For example, if we declare an integer r x inside a function, then that
variable is unknown to the rest of the program.

#include<stdio.h>
void main()
{
int x=10,i=0;
printf(“valueofxoutsidethewhileloopis%d”,x);
while(i<3)
{
int x=i;
printf(“\nvalueofxinsidewhileloopis%d”,x);
i++;
}
printf(“\nvalueofxoutsidethewhileloopis%d”,x);
}

Output:
valueofxoutsidethewhileloopis10
value of x inside whileloop is 0
valueofx inside whileloop is1
valueofxinsidewhileloop is2
valueofxoutsidethewhileloopis10

6.2 FUNCTION SCOPE


Function scope indicates that a variable is active and visible from the beginning to the
end of the function. Function scope is available with the goto label names. This means that the
programmer cannot have the same label names inside a function

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 21


Programming in C (1BEIT105)

Example:
void main()
{
..
..
loop:/*a goto lable has function scope*/
.
.
.
goto loop;
.
.
}
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 with the main()
function.

6.3 PROGRAM SCOPE


Variable declared within the function are called local variables. These are unknown to
the other functions. If we want a function to access some variables which are not passed to it
as arguments, then declare those variables outside any function blocks. Such a variables are
commonly known as global variables and can be accessed from any point in the program.
Global variables are created at the beginning of the program execution and remains in
existence throughout the period of execution of the program. It is declared outside all the
functions including main().

#include<stdio.h>
int x=10;
void print();
void main()
{
printf(“valueofxinsidemain()is%d”,x);

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 22


Programming in C (1BEIT105)
int x=2;
printf(“\nvalueoflocalvariablexinthemain()is%d”,x);
print();
}
void print()
{
printf(“\nvalue ofx inthe print()functionis%d”,x);
}

Output:
Value of x inside main() is10
value of local variable x in the main()is2
value of x in the print() functionis10.

From the example we can see that local variable over write the value of global variables.
6.4 FILE SCOPE
When the global variable is accessible until the end of the file, the variable is said to
have file scope. To allow a variable to have the file scope, declare that variable with the static
keyword before specifying its data type:
Static int x=10;
A global static variable can be used anywhere from the file in which it is declared but it not
accessible by any other file. Such variable are useful when the programmer writes his own
header file.

7. STORAGE CLASS
Storage Class defines the scope or visibility and life time of variables and functions
declared within a C program. It also gives the following information about the variable or the
function:

 It determines the part of memory where storage space will be allocated for that
variable or function.
 It specifies how long the storage allocation will continue to exist for that function or
variable

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 23


Programming in C (1BEIT105)
 It specifies the scope of the variable or function.
 It specifies whether r the variable or function has internal, external or no linkage.
 It specifies whether the variable will be automatically initialized to zero or to any
intermediate value.

General Syntax: <storage_class_specifier> <datatype> <variablename>

7.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.
Example: auto int x;
It is deleted when the block in which x is declared is exited.
 Al l local variable declared with in a function belong to automatic storage class by
default.
 Scope of this variable is local to the block in which it is declared.
 These 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.
Ex:
#include<stdio.h>
void func1()
{
int a=10;
printf(“a=%d”,a);
}
void func2()
{

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 24


Programming in C (1BEIT105)
int a=20;
printf(“a=%d”,a);
}
void main()
{
int a=30;
func1();
func2();
printf(“a=%d”,a);
}
Output:
a=10
b=20
c=30

7.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. The maximum size of the variable is equal to the register size. It is
declared as follows:
register int x;
Register variables are used when quick access to the variable is needed. Each time a
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.
Example:
#include<stdio.h>
int exp(int a,int b);
void main()
{
int a=3,b=5,res;
res=exp(a,b);
printf(“%dtothepowerof%d=%d”,a,b,res);
}
int exp(int a,int b)

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 25


Programming in C (1BEIT105)
{
register int res=1;
int i;
for(i=1;i<=b;i++)
res=res*a;
return res;
}

Output:
3 to the power of 5=243

7.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 variable in one of
the program files. To declare a variable x as extern write,
extern int x;
Memory is allocated for external variables when the program begins execution, and
remains allocated until the program terminates. They have global scope i.e., these variables
are visible and accessible from all the functions in the program.
Example:
//FILE1.c
#include<stdio.h>
#include<FILE2.C>
int x;
void print(void);
int main()
{
x=10;
printf(“\n x in FILE1=%d”,x);
print();
return0;
}
//FILE2.c
#include<stdio.h>

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 26


Programming in C (1BEIT105)
extern int x;
void print(void);
void print()
{
printf(“\nxinFILE2=%d”,x);
}
main()
{
//statements
}
Output
x in FILE1=10
x in FILE2=10

7.4 static Storage Class


While auto is the default storage class for all local variables, static is the default storage
class for all global variables. They have life time over the entire program.
static int x=10;

Static variables when defined within a function are initialized at the run time. When a static
variable is not explicitly initialized by the programmer, then it is automatically initialized to
zero when memory is allocated for it.
#include<stdio.h>
void print(void);
int main()
{
printf(“first call for print()\n”);
print();
printf(“\n second call for print()”);
print();
printf(“\n third call for print()”);
print();
return0;
}

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 27


Programming in C (1BEIT105)
void print()
{
static int x;
int y=0;
printf(“Staticintegervariablex=%d”,x);
printf(“\ninteger variabley=%d”,y);
x++;
y++;
}

Output:
First call for print()
Static integer variablex=0
Integer variable y=0

Second call for print()


Static integer variablex=1
integer variable y=0

Third call for print()


Static integer variable x=0
integer variable y=0

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 28


Programming in C (1BEIT105)

8. RECURSIVE FUNCTIONS
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. Every recursive
solution has two major cases:
 Base Case: Here, the problem is simple enough to be solved directly with out making
any further call to the same function
 Recursive Case: Here, first the problem is divided into smaller sub-parts, function call
itself to obtain the solution for the sub-parts and the result is obtained by the
combining the solution of simpler sub-parts.
Example1: Factorial of a number
Factorial of n is the product of all positive descending integers. Factorial of n is denoted by n!.
For example: 5!=5*4*3*2*1=120
3!=3*2*1= 6
Base case is when n=1, the result is 1. i.e. 1!=1
Recursive case is factorial(n)=n*factorial(n-1)

5!
=5*4!
=5*4*3!
=5*4*3*2!
=5*4*3*2*1!

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 29


Programming in C (1BEIT105)
=5*4*3*2*1
Program:
#include<stdio.h>
int factorial(int n)
{
if(n== 0)
return1;
else
return
(n*factor
al(n-1));
}
void main()
{
int number, fact;
printf("Enter a number: ");
scanf("%d",&number);
fact=factorial(number);
printf("Factorial of %d is %d\n", number, fact);
getch();
}
Example2: Greatest Common Divisor
GCD (GreatestCommonDivisor) of two numbers is the largest number that divides both of them.
GCD can be found by using Euclid’s algorithm that states
GCD(a,b)=b if b divides a GCD (b, a modb)
otherwise
Working: a=62 b=8
GCD(62,8)
Rem= 62%8 =6
GCD(8,6)
Rem= 8%6=2
GCD(6,2)
Rem=6%2=0
Return 2
[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 30
Programming in C (1BEIT105)

Program:
#include<stdio.h>
int GCD(int, int);
void main()
{
int n1,n2,res;
printf(“enternumber1and2”);
scanf(“%d%d”,&n1,&n2);
res=GCD(n1,n2):
printf(“GCDof%dand%dis%d”,n1,n2,res);
getch();
}
int GCD (int x,int y)
{
int rem;
rem=x%y;

if(rem==0)
return y;
else
return(GCD(y,rem));
}
Example3:FINDING EXPONENTS

EXP(x,y) = 1 y=0
X*EXP(x,y-1) otherwise

Working:
EXP(2,3)= 2*EXP(2,2)
=2*2*EXP(2,1)
=2*2*2 *EXP(2,0)
=2*2*2*1 =8

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 31


Programming in C (1BEIT105)

#include <stdio.h>
int exp(int,int);
void main()
{
int num1,num2,res;
printf("Entertwonumbers:");
scanf("%d, %d", &num1,&num2);
res= exp(num1,num2);
printf(“Result=%d", res);
}

int exp (int x,int y)


{
if(y== 0)
return 1;
else
return x* exp(x,y-1);
}

Example4: FIBONACCI SERIES


The Fibonacci series can be given as the following

0 1 1 2 3 5 8 13 21 ……..
Third number of the series is the sum of the first and second terms and go on. The general formula
to do so can be given as follows.

FIB(n)= 0 ifn=0
1 ifn=1
FIB(n-1)+FIB(n-2) otherwise

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 32


Programming in C (1BEIT105)

#include<stdio.h>
int fibonacci(int);
void main()
{
inti,n,res;
printf("Enterthevalueofn:");
scanf("%d",&n);
for(i=0;i<terms;i++)
{
res=fibonacci(n);
printf("%d",res);
}
}

int fibonacci(intn)
{
if(n== 0)
return 0;
elseif(n==1);
return 1;
else
{
return fibonacci(n-1)+fibonacci(n-2);
}

8.1 TYPES OF RECURSION

1. Direct Recursion: A function is said to be directly recursive if it explicitly calls itself.


Here, Func() calls itself for all positive values of n, so it is said to be a directly recursive
function.

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 33


Programming in C (1BEIT105)

2. Indirect Recursion: A function is said to be indirectly recursive if it contains a call to


another function which ultimately calls it. In the example, two function are indirectly
recursive as they both call each other.

3. Tail Recursion: A recursive function is said to be tail recursive if no operations are


pending to be performed when the recursive function returns to its caller. Tail recursive
functions are highly desirable because they are much more efficient to use as the amount
of information that has to be stored on the system stack is independent of the number of
recursive calls. Below is an example of tail recursion

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 34


34
Programming in C (1BEIT105)

A non tail recursive function is the one that has a pending operation to be performed.
Information about pending operation must be stored, so the amount of information directly
depends on the number of calls. Below is an example of non tail recursion

[Link] and Tree Recursion: A recursive function is said to be linearly recursive when the
pending operation (if any) does not make another recursive call to the function. The factorial
function is a linearly recursive as the pending operation involves only multiplication to be
performed and does not involve another recursive call. A recursive function is said to be tree
recursive if the pending operation makes another recursive call to the function. Fibonacci
function is tree recursive because the pending operations recursively calls the fib function.

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 35


35
Programming in C (1BEIT105)

TOWER OF HONAI: The tower of Hanoi is one of the main applications of recursion.
Consider three rings mounted on pole A. The problem is to move all these rings from pole A to
pole C while maintaining the same order. Smaller disk must always come above the larger disk.

Base Case :if n=1 move the ring from A to cusing Basspare
Recursive Case:
 Moven-1 rings from A to B using C as spare
 Move the one ring left on A to C using B as spare
 Moven-1rings from B to C using A as spare

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 36


36
Programming in C (1BEIT105)

Program:

#include <stdio.h>
#include<conio.h>
void hanoi(int,char,char,char);
void main()
{

int num;
clrscr();
printf("\nENTERNUMBEROFDISKS:");

scanf("%d",&num);

printf("\nTOWEROFHANOIFOR%dNUMBEROFDISKS:\n",num);

hanoi (num,'A','B','C');

getch();

void hanoi(int n,char source,char dest,char spare)

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 37


37
Programming in C (1BEIT105)
{

if(n==1)

printf("\nMOVEDISKFROM%cTO%c",from,other);

else

hanoi(n-1,source,dest,spare);
hanoi(1,source,dest,spare);
hanoi(n-1,spare,dest,source

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 38


38
Programming in C (1BEIT105)

4. automatic (local) variables:


These are defined inside the functions and their lifetime is local to the function in which it has
been defined. By default, all the variables are of type automatic only. These variables are also
called as local or internal variables. The auto keyword can be used to define automatic variables.
/* Example for automatic variables*/
#include<stdio.h>
void f1(void);
void f2(void);
void main()
{
int x=7; /* automatic or local variable*/
clrscr();
f1();
f2();
printf("\nx=%d",x);
getch();
}
void f1(void)
{
int x=17; /*local variable*/
printf("\nx=%d",x);
}
void f2(void)
{
int x=177; /* local variable*/
printf("\nx=%d",x);
}

o/p:
x=17
x=177
x=7

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 39


39
Programming in C (1BEIT105)

5. global (public) variables:


These are defined outside the functions and their lifetime is entire C program including main() and
other user defined functions. These are used to share data between many functions in a c program.
These are also called as global or public or external variables.
Example1:
int x=0; /* global variable*/
void f1(void)
void main()
{
x++;
printf(“\n x=%d”,x);
f1()
printf(“\n x=%d”,x);
getch();
}
void f1(void)
{
x++;
}

o/p:
x=1
x=2

6. static variables:
These are defined inside the function with the keyword static. These are visible with the function
in which they are defined and entire c program. Once, these variables become active then entire c
program they go on updating.
Example:
void test(void);
void main()
{
int i;

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 40


40
Programming in C (1BEIT105)
for(i=1;i<=3;i++)
{
test();
}
getch();
}
void test(void)
static int x=0; /* static variable*/
x++;
printf(“\n x=%d”,x);
}

o/p:
x=1
x=2
x=3

7. register variables:
These are defined inside or outside the function by using a keyword register. These variables will
occupy space from CPU’s register instead of computer’s primary memory RAM. These variables
used to store frequently required data by processors, so that the data stored in register can fetched
in less time with higher speed.
Example:
void main()
{
register int i, count=0; /* register variables*/
clrscr();
for(i=1;i<=100;i++)
{
count++;
}
getch();
}

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 41


41
Programming in C (1BEIT105)
RECURSION VS ITERATION

Question Bank on Functions


1. Write a C program to swapping of 2 numbers using call by reference and call by value.
2. Discuss the implementation of user defined function with suitable example.
3. Explain the working of recursion with suitable example.
4. Define Function. Explain the type of functions based on parameters.
5. Write a C program to sort the elements using bubble sort technique by passing arrays as a function
arguments.
6. Define recursion. Write a C program to find the factorial of ‘n’ using recursion.
7. Discuss storage classes in C with example.
8. Discuss in details the parts of user defined functions.
9. Explain function declaration and function definition with example.
10. Explain categories of user defined functions.
11. Explain function call, function definition and function prototype with syntax and example.
12. Write a C program to implement Binary Search for integers.
13. Write a c-program using functions to generate the Fibonacci series.
14. Write a c-program using function to check whether the given number is prime or not.
15. Explain categories of user defined function.

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 42


42
Programming in C (1BEIT105)
POINTERS CONT… (CHAPTER 2)
1. Pointers to Functions in C
1.1 Definition:
A function pointer is a pointer that stores the address of a function. It allows calling a
function indirectly or passing a function as an argument to another function.
1.2 Declaration Syntax:
return_type (*ptr_name)(parameter_list);
Example:
int (*fp)(int, int);
where `fp` is a pointer to a function taking two `int` arguments and returning an `int`.
1.3 Assigning a Function to Pointer
Function names represent their addresses.
int add(int a, int b)
{
return a + b;
}
int (*fp)(int, int) = add; // or fp = &add;
1.4 Calling Function Using Pointer
int result = fp(5, 10); // Preferred
// OR
int result = (*fp)(5, 10); // Also valid
1.5 Passing Function Pointer as Argument (Callback Function)
Used when one function calls another through a pointer.
#include <stdio.h>
void display(int (*operation)(int, int), int x, int y)
{
printf("Result = %d\n", operation(x, y));
}
int add(int a, int b)
{
return a + b;
}
int main()
{

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 43


43
Programming in C (1BEIT105)
display(add, 5, 10);
return 0;
}
`display()` accepts a function pointer and calls it inside.
1.6 Function Pointer as Return Type
A function can return a pointer to another function.
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
int (*selectOperation(char op))(int, int)
{
if (op == '+') return add;
else return sub;
}
int main()
{
int (*fp)(int, int) = selectOperation('+');
printf("%d\n", fp(10, 5)); // Output: 15
}
1.7 Array of Function Pointers
Used when multiple functions have the same prototype.
#include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 44


44
Programming in C (1BEIT105)
}
int mul(int a, int b)
{
return a * b;
}
int (*ops[3])(int, int) = {add, sub, mul};
int main()
{
int x = 10, y = 5;
printf("Add = %d\n", ops[0](x, y));
printf("Sub = %d\n", ops[1](x, y));
printf("Mul = %d\n", ops[2](x, y));
}
1.8 Using `typedef` for Simplification
Typing function pointer syntax repeatedly can be messy — use `typedef`:
typedef int (*operation)(int, int);
int add(int a, int b)
{
return a + b;
}
int main()
{
operation fp = add;
printf("%d\n", fp(3, 4));
}
Use in Library Functions (Example: `qsort()`)
C’s built-in `qsort()` uses a function pointer as a comparison function.
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b)
{
return (*(int*)a - *(int*)b);
}

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 45


45
Programming in C (1BEIT105)
int main()
{
int arr[] = {5, 2, 8, 3};
int n = sizeof(arr)/sizeof(arr[0]);
qsort(arr, n, sizeof(int), compare);
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
}
Here, `compare` is a function pointer argument.
Common Mistakes
1. Forgetting parentheses in declaration
2. Correct: `int (*fp)(int, int);`
3. Wrong: `int *fp(int, int);` (declares a function returning a pointer, not a pointer to a function)
4. Mismatching function signatures
5. Pointer’s parameter list and return type must match the target function’s prototype.
Memory View (Simplified)
+---------------------+
| Function Code | <-- add()
+---------------------+

|
+--------------+
| fp (pointer) | --> holds address of add()
+--------------+
1.9 Advantages
1. Supports **callbacks**
2. Enables **runtime function selection**
3. Used in **drivers, GUI, and OS kernels**
4. Reduces repetitive code

Adds flexibility and modularity


Real-World Example: Menu-Driven Program
#include <stdio.h>
int add(int a, int b)
{

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 46


46
Programming in C (1BEIT105)
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
int mul(int a, int b)
{
return a * b;
}
int main()
{
int choice, x, y;
int (*fp[])(int, int) = {add, sub, mul};
printf("Enter 2 numbers: ");
scanf("%d %d", &x, &y);
printf("0:Add 1:Sub 2:Mul\nChoice: ");
scanf("%d", &choice);
printf("Result = %d\n", fp[choice](x, y));
}
Quick Recap Table**

| Concept | Syntax | Example |


| ----------------- | --------------------------- | ------------------------- |
| Declare pointer | `ret (*p)(args)` | `int (*fp)(int, int);` |
| Assign function | `p = func;` | `fp = add;` |
| Call function | `p(args)` | `fp(2,3);` |
| Pass as argument | `void f(int (*)(int,int));` | `f(add);` |
| Return pointer | `ret (*f())(args)` | `int (*f())(int,int);` |
| Array of pointers | `ret (*arr[])(args)` | `int (*ops[3])(int,int);` |

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 47


47
Programming in C (1BEIT105)
2. Dynamic Memory Allocation in C
Dynamic memory allocation means allocating memory **at runtime** (instead of compile time).
It allows programs to **request and release memory** from the heap dynamically.
All DMA functions are defined in the header file:
#include <stdlib.h>
2.1. malloc() — Memory Allocation
Syntax:
ptr = (type*) malloc(size_in_bytes);
Description:
* Allocates a **block of memory** of given size (in bytes).
* Returns a **void pointer** to the first byte of allocated memory.
* Returns **NULL** if memory allocation fails.
* Memory is **uninitialized** (contains garbage values).
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p;
p = (int*) malloc(5 * sizeof(int)); // allocates memory for 5 integers
if (p == NULL) {
printf("Memory not allocated.\n");
return 0;
}
for (int i = 0; i < 5; i++) {
p[i] = i + 1;
}
for (int i = 0; i < 5; i++) {
printf("%d ", p[i]);
}
free(p); // always free after use
return 0;
}

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 48


48
Programming in C (1BEIT105)
2.2. calloc() — Contiguous Allocation
Syntax:
ptr = (type*) calloc(num_elements, size_of_each_element);
Description:
* Allocates memory for **multiple elements** (array-like).
* Initializes all bytes to **zero**.
* Returns a **void pointer** to the allocated memory.
* Returns **NULL** if allocation fails.
Example:
int *p = (int*) calloc(5, sizeof(int)); // allocates memory for 5 integers, all initialized to 0
2.3. realloc() — Reallocation
Syntax:
ptr = (type*) realloc(old_ptr, new_size_in_bytes);
Description:
* Used to **resize** (increase or decrease) previously allocated memory block.
* Preserves existing data up to the smaller of old/new sizes.
* Returns a pointer to new memory block (may move to a new address).
* If fails, returns **NULL**, but the original memory is not freed.
Example:
int *p = (int*) malloc(3 * sizeof(int));
p = (int*) realloc(p, 5 * sizeof(int)); // resize memory to hold 5 integers
2.4. free() — Deallocation
Syntax:
free(ptr);
Description:
* Frees the dynamically allocated memory pointed by `ptr`.
* After `free()`, the pointer becomes **dangling** — set it to `NULL`.
* Prevents **memory leaks**.
Example:
free(p);
p = NULL; // good practice

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 49


49
Programming in C (1BEIT105)
Summary Table

| Function | Purpose | Initializes Memory? | Parameters | Returns |


| ----------- | -------------------------------- | ------------------- | ----------------------------- | ------- |
| `malloc()` | Allocates single block | ❌Garbage | size (bytes) | `void*` |
| `calloc()` | Allocates multiple blocks | ✅ Zero | no. of elements, size of each |
`void*` |
| `realloc()` | Changes size of allocated memory | Keeps old data | old pointer, new size |
`void*` |
| `free()` | Frees allocated memory |— | pointer | void |

Common Mistakes
❌ Forgetting to `free()` memory → causes memory leaks
❌ Using memory after freeing → causes dangling pointer errors
❌ Not checking if allocation returned `NULL`
✅ Always:
if (ptr == NULL)
{
printf("Memory allocation failed!");
}
Example: Full Program Using All DMA Functions**
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p, n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
p = (int*) malloc(n * sizeof(int));
if (p == NULL) {
printf("Memory allocation failed!\n");
return 0;
}
printf("Enter elements:\n");
for (i = 0; i < n; i++)

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 50


50
Programming in C (1BEIT105)
scanf("%d", &p[i]);
// Resize memory
p = (int*) realloc(p, (n + 2) * sizeof(int));
printf("Enter 2 more elements:\n");
for (i = n; i < n + 2; i++)
scanf("%d", &p[i]);
printf("Elements are:\n");
for (i = 0; i < n + 2; i++)
printf("%d ", p[i]);
free(p);
p = NULL;
return 0;
}
Real-life Uses of DMA
✅ When array size is not known at compile time
✅ When handling large datasets (like file input, structures, etc.)
✅ For implementing linked lists, trees, graphs
✅ For dynamic data buffers (networking, strings, etc.)

[Link] CSE(DS), BLDEACET,Vijayapur - 586103 Page 51


51

You might also like