SlideShare a Scribd company logo
1
UNIT - IV
MODULAR PROGRAMMING
Function and Parameter Declarations: Function definition, types of functions, declaration
and definition of user defined functions, its prototypes and parameters, calling a function.
Variable Scope, Storage classes, recursive functions, Array as function arguments
S.NO TOPIC PAGE NUMBER
1. Function definition 2
2. Types of functions 2
3. Components of function 3
4. Categories of functions 7
5. Storage class 9
6. Variable Scope 12
7. Recursive function 14
8. Arrays as function
arguments
16
2
FUNCTION DEFINITION:
• A function is a group of statements/self-defined block of statements to perform a
specific task.
• Every C program has at least one function i.e main()
• The above figure shows a main function calling func1(), func1 in turn calls func2() and
it goes on. A single function can call as many functions as needed.
• The terminologies to be known while using functions are:
calling function – A function that uses another function
called function – the function which is being called by another function
return – a called function returns some value back to the calling function/ output of a
function
paramters/arguments – the input to the function
TYPES OF FUNCTIONS:
o Standard library functions
o User-defined functions
Built-in functions or Library functions:Build-in functions are predefined functions are
supplied along with the complier whose functionality has been already defined.
Example: printf(), scanf(), getch(), sqrt() etc.
User defined functions:These functions are defined by the user. In these functions the
programmer or developer writes his own logic to perform particular task. These functions are
called from the main() function by using the function call.
Advantages of Functions:
• The major advantages of functions are code reusability. The same code is executed
repeatedly.
• Reduces length of the program
• Debugging is simple to perform
• Functions generates modularity
• Takes less time to write a program
• It saves memory.
Disadvantages of Functions:
3
• It is less portable
• Function doesn’t return more than one value at a time. Its needs pointer for such case
• The only disadvantage to a function is that it incurs a function call
• There may not be any speed advantage.
Function Definition :
Syntax:
Return-type function-name (parameters or arguments list)
{
Local declarations;
Executable statements;
Return statement;
}
• Return-type is a valid data type
• Function-name is a valid variable-name which satisfied the rules of declaring a variable
• List of arguments are separated by a comma and they are called formal parameters.
int add (int a, int b)
{
int c;
c=a+b;
return(c);
}
FUNCTION COMPONENTS:
Every function is associated with the following
• Function Declaration or prototype
• Function Parameters
• Function Definition (Function Header + Function Body)
• Return Statement
• Function Call
FUNCTION PROTOTYPE (OR) FUNCTION DECLARATION:
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’ll return
to the calling function. Function must be declared before using it in a program.
Syntax:
return_data_type function_name (data_type variable1, data_type variable2,..);
Example:
int add(int a, int b);
4
float average(float x, float y);
void display(void); //function with no arguments and no return type
• Function_name – must be a meaningful name that will specify the task the function
should perform.
• return_data_type – data type of the result that will be returned to the calling function
• arguments/parameters – the variables that are passed to the calling function along
with its data types
Rules for function declaration:
1. ends with a semicolon
2. function declaration is global
3. use of variable names in function declaration is optional (ex. int add(int, int);)
4. a function can’t be declared within the body of another function
5. function with void in parameter list doesn’t accept any inputs
6. function with void as the return type doesn’t return any values
7. if we do not specify any return type, then by default int is the return type
FUNCTION DEFINITION:
A function definition describes what a function does, how actions are achieved and how it is
used. It comprises two parts:
• Function header
• Function body
Syntax:
return_data_type function_name(data_type variable1, data_type variable2,…)
{
…..
Statements
….
return (variable);
}
• Function header - return_data_type function_name(data_type variable1, data_type
variable2,…)
• Function body –the portion of the program within { } which contains the code to
perform the specific task
• The list of variables in the function header is known as formal parameters.
• The programmer may skip the function declaration in case the function is defined
before being used.
Example:
int a=2, b=3;
5
int c;
c=a+b;
return(c);
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 part of that function. Once the
called function is executed, the program control passes back to the calling function.
Syntax:
variable=function_name(variable1, variable2,….);//function that returns a value
(or)
function_name(variable1, variable2,….); //function that doesn’t return any value
Example:
d =add(10,20);
avg = average(a,b);
display(); //function with no arguments and no return type
Rules for function call:
1. Function name and type of arguments must be same as that of declaration and definition
2. If the parameters passed is more than specified, the extra parameters will be discarded
3. If the parameters passed are less than expected, then the unmatched arguments will be
initialized to some garbage value
4. Names of variables in function declaration, definition and function call may vary
5. If the data types does not match then it’ll be initialized to some garbage value or a
compile time error will be generated
6. Arguments may be passed in the form of expression. (ex. increment(x+y);)
7. The list of variables in the function call is known as actual parameters.
RETURNING A VALUE:
The return statement is used to terminate the execution of a function and return the control to
the calling function. A return statement may or may not return a value to the calling function.
Syntax:
return <expression>;
For functions that have no return statement, the control automatically returns to the calling
function after the last statement of the called function is executed.A function that does not
return anything is indicated by the keyword void.
Function parameters:
The parameters are classified into two types;
• Actual Parameters
• Formal Parameters or dummy parameters
Actual parameters - The parameters specified in the function call are called actual parameters.
c= add(10,20); //10 and 20 are actual parameters.
6
Formal parameters - The parameters specified in the function declaration are called formal
parameters.
int add (int a, int b); //a and b are called formal parameters.
Rules:
• Number of arguments in the actual parameters and formal parameters must be
equal.
• The data type of each argument in actual and formal parameters must be same.
• The order of actual and formal parameter must be important.
Sample program for addition of 2 numbers:
#include<stdio.h>
//FUNCTION DECLARATION
int sum(int a, int b);
int main()
{
int a, b, c;
printf(“Enter the values of a & b:”);
scanf(“%d %d”,&a,&b);
//FUNCTION CALL
c = sum(a,b);
printf(“Sum is %d”, c);
return 0;
}
//FUNCTION DEFINITION
int sum(int x, int y) //FUNCTION HEADER
{ //FUNCTION BODY
int z;
z = x+y;
return z;
}
Sample program with multiple return statements:
#include<stdio.h>
//FUNCTION DECLARATION
int compare(int a, int b);
int main()
{
int a, b, res;
printf(“Enter the values of a & b:”);
scanf(“%d %d”,&a,&b);
//FUNCTION CALL
7
res = compare(a,b);
if(res==0)
printf(“EQUAL”);
else if (res==1)
printf(“a is greater than b”);
else
printf(“a is less than b”);
return 0;
}
//FUNCTION DEFINITION
int compare(int x, int y) //FUNCTION HEADER
{ //FUNCTION BODY
if(x==y)
return 0;
else if(x>y)
return 1;
else
return -1;
}
CATEGORIES OF FUNCTIONS:
User-defined functions can be categorized as:
• Function with no arguments and no return value
• Function with no arguments and return value
• Function with arguments and no return value
• Function with arguments and return value
Functions with no arguments and no return value:
#include <stdio.h>
void sum(void);
int main()
{
sum();
return 0;
}
void sum()
{
int a,b,c;
printf(“Enter the values of a & b:”);
8
scanf(“%d %d”,&a,&b);
c = a+b;
printf(“sum is %d”, c);
}
The sum() function takes input from the user, finds the sum of the 2 numbers and displays it
on the screen.The empty parentheses in sum(); statement inside the main() function indicates
that no argument is passed to the function.The return type of the function is void. Hence, no
value is returned from the function.
Function with no arguments and return value:
#include <stdio.h>
int sum(void);
int main()
{
int c;
c = sum();
return 0;
}
int sum()
{
int a,b,c;
printf(“Enter the values of a & b:”);
scanf(“%d %d”,&a,&b);
c = a+b;
return c;
}
The empty parentheses in c=sum(); statement indicates that no argument is passed to the
function. And, the value returned from the function is assigned to c.Here, the sum() function
takes input from the user and returns the result.
Function with arguments and no return value:
#include <stdio.h>
void sum(int, int);
int main()
{
int a,b,c;
printf(“Enter the values of a & b:”);
scanf(“%d %d”,&a,&b);
9
sum(a, b);
return 0;
}
void sum(int a, int b)
{
int c;
c = a+b;
printf(“sum is %d”, c);
}
The 2 numbers entered by the user is passed to sum() function.Here, the sum() function adds
the 2 numbers and displays the appropriate result.
Function with arguments and return value:
#include <stdio.h>
int sum(int, int);
int main()
{
int a,b,c;
printf(“Enter the values of a & b:”);
scanf(“%d %d”,&a,&b);
c = sum(a, b);
return 0;
}
int sum(int a, int b)
{
int c;
c = a+b;
return c;
}
The input from the user is passed to sum() function.The sum() function adds the 2 numbers and
the result is returned to the main() function in which the result is displayed.
STORAGE CLASSES:
A storage class defines the scope (visibility) and life-time of variables and/or functions within
a C Program. They precede the type that they modify. We have four different storage classes
in a C program:
• auto
• register
10
• static
• extern
Storage Default value Scope Life
Auto Memory An unpredictable
value, which is often
called a garbage
value
Local to the block in
which the variable is
defined
Till the control remains
within the block in which
the variable is defined
Static Memory Zero Local to the block in
which the variable is
defined
Value of the variable
persists between different
function calls
External Memory Zero Global As long as the program’s
execution. Doesn’t came to
an end
Register CPU Registers Garbage Value Local to the block in
which the variable is
defined
Till the control remains
within the block in which
the variable is defined
The auto Storage Class:
• The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can only be used
within functions, i.e., local variables.
The register Storage Class:
• The register storage class is used to define local variables that should be stored in a
register instead of RAM. This means that the variable has a maximum size equal to the
register size (usually one word) and can't have the unary '&' operator applied to it (as it
does not have a memory location).
{
register int miles;
}
11
• The register should only be used for variables that require quick access such as
counters. It should also be noted that defining 'register' does not mean that the variable
will be stored in a register. It means that it MIGHT be stored in a register depending on
hardware and implementation restrictions.
The static Storage Class:
• The static storage class instructs the compiler to keep a local variable in existence
during the life-time of the program instead of creating and destroying it each time it
comes into and goes out of scope. Therefore, making local variables static allows them
to maintain their values between function calls.
• The static modifier may also be applied to global variables. When this is done, it causes
that variable's scope to be restricted to the file in which it is declared.
#include <stdio.h>
void func(void);
static int count = 5; /* global variable */
main() {
while(count--) {
func();
}
return 0;
}
void func( void ) {
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %dn", i, count);
}
Output:
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
The 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. When you use 'extern', the variable cannot be initialized
however, it points the variable name at a storage location that has been previously
defined.
12
• When you have multiple files and you define a global variable or function, which will
also be used in other files, then extern will be used in another file to provide the
reference of defined variable or function. Just for understanding, extern is used to
declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more files sharing
the same global variables or functions as explained below.
First File: main.c
#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
Second File: support.c
#include <stdio.h>
extern int count;
void write_extern(void) {
printf("count is %dn", count);
}
Here, extern is being used to declare count in the second file, where as it has its definition in
the first file, main.c. Now, compile these two files as follows −
$gcc main.c support.c
It will produce the executable program a.out. When this program is executed, it produces the
following result −
count is 5
VARIABLE SCOPE:
Variable Scope is a region in a program where a variable is declared and used. So, we can have
three types of scopes depending on the region where these are declared and used:
• Local variables are defined inside a function or a block
• Global variables are outside all functions
• Formal parameters are defined in function parameters
13
Local variables:
• Variables that are declared inside a function or a block are called localvariables and are
said to have localscope.
• These local variables can only be used within the function or block in which these are
declared.
• We can use (or access) a local variable only in the block or function in which it is
declared. It is invalid outside it.
• Local variables are created when the control reaches the block or function containing
the local variables and then they get destroyed after that.
#include <stdio.h>
void fun1()
{
int x = 4; /*local variable of function fun1*/
printf("%dn",x);
}
int main()
{
int x = 10;/*local variable of function main*/
{
int x = 5;/*local variable of this block*/
printf("%dn",x);
}
printf("%dn",x);
fun1();
}
Output:
5
10
4
Global variables:
• Variables that are defined outside of all the functions and are accessible throughout the
program are global variables and are said to have global scope.
• Once declared, these can be accessed and modified by any function in the program.
• We can have the same name for a local and a global variable but the local variable gets
priority inside a function.
#include <stdio.h>
14
int x = 10;/*Global variable*/
void fun1()
{
int x = 5; /*local variable of same name*/
printf("%dn",x);
}
int main()
{
printf("%dn",x);
fun1();
}
Output:
10
5
You can see that the value of the local variable ‘x’ was given priority inside the function ‘fun1’
over the global variable have the same name ‘x’.
Formal parameters:
• Formal Parameters are the parameters which are used inside the body of a function.
• Formal parameters are treated as local variables in that function and get a priority over
the global variables.
#include <stdio.h>
int x = 10;/*Global variable*/
void fun1(int x)
{
printf("%dn",x); /*x is a formal parameter*/
}
int main()
{
fun1(5);
}
Output:
5
Recursive function:
In C programming language, function calls can be made from the main() function, other
functions or from the same function itself. The recursive function is defined as follows...
15
A function called by itself is called recursive function.
The recursive functions should be used very carefully because, when a function called by itself
it enters into the infinite loop. And when a function enters into the infinite loop, the function
execution never gets completed. We should define the condition to exit from the function call
so that the recursive function gets terminated.
When a function is called by itself, the first call remains under execution till the last call gets
invoked. Every time when a function call is invoked, the function returns the execution control
to the previous function call.
1.Factorial of a number using recursion
#include<stdio.h>
#include<conio.h>
int factorial( int ) ;
int main()
{
int fact, n ;
printf("Enter any positive integer: ") ;
scanf("%d", &n) ;
fact = factorial( n ) ;
printf("nFactorial of %d is %dn", n, fact) ;
return 0;
}
int factorial( int n )
{
int temp ;
if( n == 0)
return 1 ;
else
temp = n * factorial( n-1 ) ; // recursive function call
return temp ;
}
Output:
16
In the above example program, the factorial() function call is initiated from main() function
with the value 3. Inside the factorial() function, the function calls factorial(2), factorial(1) and
factorial(0) are called recursively. In this program execution process, the function call
factorial(3) remains under execution till the execution of function calls factorial(2), factorial(1)
and factorial(0) gets completed. Similarly the function call factorial(2) remains under execution
till the execution of function calls factorial(1) and factorial(0) gets completed. In the same way
the function call factorial(1) remains under execution till the execution of function call
factorial(0) gets completed. The complete execution process of the above program is shown in
the following figure...
17
Array as function arguments:
Just like variables, array can also be passed to a function as an argument .
#include <stdio.h>
void disp(char);
void main()
{
int x;
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
18
for ( x=0; x<10; x++)
{
/* I’m passing each element one by one using subscript*/
disp (arr[x]);
}
}
void disp( char ch)
{
printf("%ct", ch);
}
Output: a b c d e f g h I j
Passing Array using call by reference:
When we pass the address of an array while calling a function then this is called function call
by reference. When we pass an address as an argument, the function declaration should have
a pointer as a parameter to receive the passed address.
#include <stdio.h>
Void disp(int *);
void main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<10; i++)
{
/* Passing addresses of array elements*/
disp (&arr[i]);
}
}
void disp( int *num)
{
printf("%d ", *num);
}
Output:
1 2 3 4 5 6 7 8 9 0

More Related Content

PDF
Functions-Computer programming
nmahi96
 
PDF
Function
Kathmandu University
 
PPTX
Functions in C
Kamal Acharya
 
PPTX
function of C.pptx
shivas379526
 
DOC
Unit 4 (1)
psaravanan1985
 
DOCX
Introduction to c programming
AMAN ANAND
 
PPTX
Functions
Golda Margret Sheeba J
 
PPTX
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
vekariyakashyap
 
Functions-Computer programming
nmahi96
 
Functions in C
Kamal Acharya
 
function of C.pptx
shivas379526
 
Unit 4 (1)
psaravanan1985
 
Introduction to c programming
AMAN ANAND
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
vekariyakashyap
 

Similar to PSPC-UNIT-4.pdf (20)

PPTX
C and C++ functions
kavitha muneeshwaran
 
PPT
arrays.ppt
Bharath904863
 
PDF
FUNCTIONS IN C PROGRAMMING.pdf
RITHIKA R S
 
PPT
User defined functions in C programmig
Appili Vamsi Krishna
 
PDF
User_Defined_Functions_ppt_slideshare.
NabeelaNousheen
 
PPTX
user-definedfunctions-converted.pptx
ZaibunnisaMalik1
 
PPTX
Detailed concept of function in c programming
anjanasharma77573
 
PPTX
Functions in C.pptx
Ashwini Raut
 
PDF
unit3 part2 pcds function notes.pdf
JAVVAJI VENKATA RAO
 
PPTX
Module 3-Functions
nikshaikh786
 
PPTX
Functions
Jesmin Akhter
 
PPTX
unit_2.pptx
Venkatesh Goud
 
PPTX
Unit-III.pptx
Mehul Desai
 
PPT
RECURSION IN C
v_jk
 
PPT
Recursion in C
v_jk
 
PDF
1.6 Function.pdf
NirmalaShinde3
 
ODP
Function
jayesh30sikchi
 
PPTX
Function in c program
umesh patil
 
PPT
function_v1fgdfdf5645ythyth6ythythgbg.ppt
RoselinLourd
 
PPT
function_v1.ppt
ssuser2076d9
 
C and C++ functions
kavitha muneeshwaran
 
arrays.ppt
Bharath904863
 
FUNCTIONS IN C PROGRAMMING.pdf
RITHIKA R S
 
User defined functions in C programmig
Appili Vamsi Krishna
 
User_Defined_Functions_ppt_slideshare.
NabeelaNousheen
 
user-definedfunctions-converted.pptx
ZaibunnisaMalik1
 
Detailed concept of function in c programming
anjanasharma77573
 
Functions in C.pptx
Ashwini Raut
 
unit3 part2 pcds function notes.pdf
JAVVAJI VENKATA RAO
 
Module 3-Functions
nikshaikh786
 
Functions
Jesmin Akhter
 
unit_2.pptx
Venkatesh Goud
 
Unit-III.pptx
Mehul Desai
 
RECURSION IN C
v_jk
 
Recursion in C
v_jk
 
1.6 Function.pdf
NirmalaShinde3
 
Function
jayesh30sikchi
 
Function in c program
umesh patil
 
function_v1fgdfdf5645ythyth6ythythgbg.ppt
RoselinLourd
 
function_v1.ppt
ssuser2076d9
 
Ad

Recently uploaded (20)

DOCX
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
PPTX
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
PPTX
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
PPTX
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
PPTX
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PPTX
A Smarter Way to Think About Choosing a College
Cyndy McDonald
 
PPTX
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
PPTX
CDH. pptx
AneetaSharma15
 
PDF
Biological Classification Class 11th NCERT CBSE NEET.pdf
NehaRohtagi1
 
PPTX
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
PDF
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
PPTX
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
PPTX
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
PDF
Module 2: Public Health History [Tutorial Slides]
JonathanHallett4
 
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
A Smarter Way to Think About Choosing a College
Cyndy McDonald
 
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
CDH. pptx
AneetaSharma15
 
Biological Classification Class 11th NCERT CBSE NEET.pdf
NehaRohtagi1
 
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
Module 2: Public Health History [Tutorial Slides]
JonathanHallett4
 
Ad

PSPC-UNIT-4.pdf

  • 1. 1 UNIT - IV MODULAR PROGRAMMING Function and Parameter Declarations: Function definition, types of functions, declaration and definition of user defined functions, its prototypes and parameters, calling a function. Variable Scope, Storage classes, recursive functions, Array as function arguments S.NO TOPIC PAGE NUMBER 1. Function definition 2 2. Types of functions 2 3. Components of function 3 4. Categories of functions 7 5. Storage class 9 6. Variable Scope 12 7. Recursive function 14 8. Arrays as function arguments 16
  • 2. 2 FUNCTION DEFINITION: • A function is a group of statements/self-defined block of statements to perform a specific task. • Every C program has at least one function i.e main() • The above figure shows a main function calling func1(), func1 in turn calls func2() and it goes on. A single function can call as many functions as needed. • The terminologies to be known while using functions are: calling function – A function that uses another function called function – the function which is being called by another function return – a called function returns some value back to the calling function/ output of a function paramters/arguments – the input to the function TYPES OF FUNCTIONS: o Standard library functions o User-defined functions Built-in functions or Library functions:Build-in functions are predefined functions are supplied along with the complier whose functionality has been already defined. Example: printf(), scanf(), getch(), sqrt() etc. User defined functions:These functions are defined by the user. In these functions the programmer or developer writes his own logic to perform particular task. These functions are called from the main() function by using the function call. Advantages of Functions: • The major advantages of functions are code reusability. The same code is executed repeatedly. • Reduces length of the program • Debugging is simple to perform • Functions generates modularity • Takes less time to write a program • It saves memory. Disadvantages of Functions:
  • 3. 3 • It is less portable • Function doesn’t return more than one value at a time. Its needs pointer for such case • The only disadvantage to a function is that it incurs a function call • There may not be any speed advantage. Function Definition : Syntax: Return-type function-name (parameters or arguments list) { Local declarations; Executable statements; Return statement; } • Return-type is a valid data type • Function-name is a valid variable-name which satisfied the rules of declaring a variable • List of arguments are separated by a comma and they are called formal parameters. int add (int a, int b) { int c; c=a+b; return(c); } FUNCTION COMPONENTS: Every function is associated with the following • Function Declaration or prototype • Function Parameters • Function Definition (Function Header + Function Body) • Return Statement • Function Call FUNCTION PROTOTYPE (OR) FUNCTION DECLARATION: 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’ll return to the calling function. Function must be declared before using it in a program. Syntax: return_data_type function_name (data_type variable1, data_type variable2,..); Example: int add(int a, int b);
  • 4. 4 float average(float x, float y); void display(void); //function with no arguments and no return type • Function_name – must be a meaningful name that will specify the task the function should perform. • return_data_type – data type of the result that will be returned to the calling function • arguments/parameters – the variables that are passed to the calling function along with its data types Rules for function declaration: 1. ends with a semicolon 2. function declaration is global 3. use of variable names in function declaration is optional (ex. int add(int, int);) 4. a function can’t be declared within the body of another function 5. function with void in parameter list doesn’t accept any inputs 6. function with void as the return type doesn’t return any values 7. if we do not specify any return type, then by default int is the return type FUNCTION DEFINITION: A function definition describes what a function does, how actions are achieved and how it is used. It comprises two parts: • Function header • Function body Syntax: return_data_type function_name(data_type variable1, data_type variable2,…) { ….. Statements …. return (variable); } • Function header - return_data_type function_name(data_type variable1, data_type variable2,…) • Function body –the portion of the program within { } which contains the code to perform the specific task • The list of variables in the function header is known as formal parameters. • The programmer may skip the function declaration in case the function is defined before being used. Example: int a=2, b=3;
  • 5. 5 int c; c=a+b; return(c); 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 part of that function. Once the called function is executed, the program control passes back to the calling function. Syntax: variable=function_name(variable1, variable2,….);//function that returns a value (or) function_name(variable1, variable2,….); //function that doesn’t return any value Example: d =add(10,20); avg = average(a,b); display(); //function with no arguments and no return type Rules for function call: 1. Function name and type of arguments must be same as that of declaration and definition 2. If the parameters passed is more than specified, the extra parameters will be discarded 3. If the parameters passed are less than expected, then the unmatched arguments will be initialized to some garbage value 4. Names of variables in function declaration, definition and function call may vary 5. If the data types does not match then it’ll be initialized to some garbage value or a compile time error will be generated 6. Arguments may be passed in the form of expression. (ex. increment(x+y);) 7. The list of variables in the function call is known as actual parameters. RETURNING A VALUE: The return statement is used to terminate the execution of a function and return the control to the calling function. A return statement may or may not return a value to the calling function. Syntax: return <expression>; For functions that have no return statement, the control automatically returns to the calling function after the last statement of the called function is executed.A function that does not return anything is indicated by the keyword void. Function parameters: The parameters are classified into two types; • Actual Parameters • Formal Parameters or dummy parameters Actual parameters - The parameters specified in the function call are called actual parameters. c= add(10,20); //10 and 20 are actual parameters.
  • 6. 6 Formal parameters - The parameters specified in the function declaration are called formal parameters. int add (int a, int b); //a and b are called formal parameters. Rules: • Number of arguments in the actual parameters and formal parameters must be equal. • The data type of each argument in actual and formal parameters must be same. • The order of actual and formal parameter must be important. Sample program for addition of 2 numbers: #include<stdio.h> //FUNCTION DECLARATION int sum(int a, int b); int main() { int a, b, c; printf(“Enter the values of a & b:”); scanf(“%d %d”,&a,&b); //FUNCTION CALL c = sum(a,b); printf(“Sum is %d”, c); return 0; } //FUNCTION DEFINITION int sum(int x, int y) //FUNCTION HEADER { //FUNCTION BODY int z; z = x+y; return z; } Sample program with multiple return statements: #include<stdio.h> //FUNCTION DECLARATION int compare(int a, int b); int main() { int a, b, res; printf(“Enter the values of a & b:”); scanf(“%d %d”,&a,&b); //FUNCTION CALL
  • 7. 7 res = compare(a,b); if(res==0) printf(“EQUAL”); else if (res==1) printf(“a is greater than b”); else printf(“a is less than b”); return 0; } //FUNCTION DEFINITION int compare(int x, int y) //FUNCTION HEADER { //FUNCTION BODY if(x==y) return 0; else if(x>y) return 1; else return -1; } CATEGORIES OF FUNCTIONS: User-defined functions can be categorized as: • Function with no arguments and no return value • Function with no arguments and return value • Function with arguments and no return value • Function with arguments and return value Functions with no arguments and no return value: #include <stdio.h> void sum(void); int main() { sum(); return 0; } void sum() { int a,b,c; printf(“Enter the values of a & b:”);
  • 8. 8 scanf(“%d %d”,&a,&b); c = a+b; printf(“sum is %d”, c); } The sum() function takes input from the user, finds the sum of the 2 numbers and displays it on the screen.The empty parentheses in sum(); statement inside the main() function indicates that no argument is passed to the function.The return type of the function is void. Hence, no value is returned from the function. Function with no arguments and return value: #include <stdio.h> int sum(void); int main() { int c; c = sum(); return 0; } int sum() { int a,b,c; printf(“Enter the values of a & b:”); scanf(“%d %d”,&a,&b); c = a+b; return c; } The empty parentheses in c=sum(); statement indicates that no argument is passed to the function. And, the value returned from the function is assigned to c.Here, the sum() function takes input from the user and returns the result. Function with arguments and no return value: #include <stdio.h> void sum(int, int); int main() { int a,b,c; printf(“Enter the values of a & b:”); scanf(“%d %d”,&a,&b);
  • 9. 9 sum(a, b); return 0; } void sum(int a, int b) { int c; c = a+b; printf(“sum is %d”, c); } The 2 numbers entered by the user is passed to sum() function.Here, the sum() function adds the 2 numbers and displays the appropriate result. Function with arguments and return value: #include <stdio.h> int sum(int, int); int main() { int a,b,c; printf(“Enter the values of a & b:”); scanf(“%d %d”,&a,&b); c = sum(a, b); return 0; } int sum(int a, int b) { int c; c = a+b; return c; } The input from the user is passed to sum() function.The sum() function adds the 2 numbers and the result is returned to the main() function in which the result is displayed. STORAGE CLASSES: A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program. They precede the type that they modify. We have four different storage classes in a C program: • auto • register
  • 10. 10 • static • extern Storage Default value Scope Life Auto Memory An unpredictable value, which is often called a garbage value Local to the block in which the variable is defined Till the control remains within the block in which the variable is defined Static Memory Zero Local to the block in which the variable is defined Value of the variable persists between different function calls External Memory Zero Global As long as the program’s execution. Doesn’t came to an end Register CPU Registers Garbage Value Local to the block in which the variable is defined Till the control remains within the block in which the variable is defined The auto Storage Class: • The auto storage class is the default storage class for all local variables. { int mount; auto int month; } The example above defines two variables with in the same storage class. 'auto' can only be used within functions, i.e., local variables. The register Storage Class: • The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location). { register int miles; }
  • 11. 11 • The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions. The static Storage Class: • The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. • The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared. #include <stdio.h> void func(void); static int count = 5; /* global variable */ main() { while(count--) { func(); } return 0; } void func( void ) { static int i = 5; /* local static variable */ i++; printf("i is %d and count is %dn", i, count); } Output: i is 6 and count is 4 i is 7 and count is 3 i is 8 and count is 2 i is 9 and count is 1 i is 10 and count is 0 The 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. When you use 'extern', the variable cannot be initialized however, it points the variable name at a storage location that has been previously defined.
  • 12. 12 • When you have multiple files and you define a global variable or function, which will also be used in other files, then extern will be used in another file to provide the reference of defined variable or function. Just for understanding, extern is used to declare a global variable or function in another file. The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below. First File: main.c #include <stdio.h> int count ; extern void write_extern(); main() { count = 5; write_extern(); } Second File: support.c #include <stdio.h> extern int count; void write_extern(void) { printf("count is %dn", count); } Here, extern is being used to declare count in the second file, where as it has its definition in the first file, main.c. Now, compile these two files as follows − $gcc main.c support.c It will produce the executable program a.out. When this program is executed, it produces the following result − count is 5 VARIABLE SCOPE: Variable Scope is a region in a program where a variable is declared and used. So, we can have three types of scopes depending on the region where these are declared and used: • Local variables are defined inside a function or a block • Global variables are outside all functions • Formal parameters are defined in function parameters
  • 13. 13 Local variables: • Variables that are declared inside a function or a block are called localvariables and are said to have localscope. • These local variables can only be used within the function or block in which these are declared. • We can use (or access) a local variable only in the block or function in which it is declared. It is invalid outside it. • Local variables are created when the control reaches the block or function containing the local variables and then they get destroyed after that. #include <stdio.h> void fun1() { int x = 4; /*local variable of function fun1*/ printf("%dn",x); } int main() { int x = 10;/*local variable of function main*/ { int x = 5;/*local variable of this block*/ printf("%dn",x); } printf("%dn",x); fun1(); } Output: 5 10 4 Global variables: • Variables that are defined outside of all the functions and are accessible throughout the program are global variables and are said to have global scope. • Once declared, these can be accessed and modified by any function in the program. • We can have the same name for a local and a global variable but the local variable gets priority inside a function. #include <stdio.h>
  • 14. 14 int x = 10;/*Global variable*/ void fun1() { int x = 5; /*local variable of same name*/ printf("%dn",x); } int main() { printf("%dn",x); fun1(); } Output: 10 5 You can see that the value of the local variable ‘x’ was given priority inside the function ‘fun1’ over the global variable have the same name ‘x’. Formal parameters: • Formal Parameters are the parameters which are used inside the body of a function. • Formal parameters are treated as local variables in that function and get a priority over the global variables. #include <stdio.h> int x = 10;/*Global variable*/ void fun1(int x) { printf("%dn",x); /*x is a formal parameter*/ } int main() { fun1(5); } Output: 5 Recursive function: In C programming language, function calls can be made from the main() function, other functions or from the same function itself. The recursive function is defined as follows...
  • 15. 15 A function called by itself is called recursive function. The recursive functions should be used very carefully because, when a function called by itself it enters into the infinite loop. And when a function enters into the infinite loop, the function execution never gets completed. We should define the condition to exit from the function call so that the recursive function gets terminated. When a function is called by itself, the first call remains under execution till the last call gets invoked. Every time when a function call is invoked, the function returns the execution control to the previous function call. 1.Factorial of a number using recursion #include<stdio.h> #include<conio.h> int factorial( int ) ; int main() { int fact, n ; printf("Enter any positive integer: ") ; scanf("%d", &n) ; fact = factorial( n ) ; printf("nFactorial of %d is %dn", n, fact) ; return 0; } int factorial( int n ) { int temp ; if( n == 0) return 1 ; else temp = n * factorial( n-1 ) ; // recursive function call return temp ; } Output:
  • 16. 16 In the above example program, the factorial() function call is initiated from main() function with the value 3. Inside the factorial() function, the function calls factorial(2), factorial(1) and factorial(0) are called recursively. In this program execution process, the function call factorial(3) remains under execution till the execution of function calls factorial(2), factorial(1) and factorial(0) gets completed. Similarly the function call factorial(2) remains under execution till the execution of function calls factorial(1) and factorial(0) gets completed. In the same way the function call factorial(1) remains under execution till the execution of function call factorial(0) gets completed. The complete execution process of the above program is shown in the following figure...
  • 17. 17 Array as function arguments: Just like variables, array can also be passed to a function as an argument . #include <stdio.h> void disp(char); void main() { int x; char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
  • 18. 18 for ( x=0; x<10; x++) { /* I’m passing each element one by one using subscript*/ disp (arr[x]); } } void disp( char ch) { printf("%ct", ch); } Output: a b c d e f g h I j Passing Array using call by reference: When we pass the address of an array while calling a function then this is called function call by reference. When we pass an address as an argument, the function declaration should have a pointer as a parameter to receive the passed address. #include <stdio.h> Void disp(int *); void main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; for (int i=0; i<10; i++) { /* Passing addresses of array elements*/ disp (&arr[i]); } } void disp( int *num) { printf("%d ", *num); } Output: 1 2 3 4 5 6 7 8 9 0