0% found this document useful (0 votes)
20 views110 pages

Functions in C

Uploaded by

padma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views110 pages

Functions in C

Uploaded by

padma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 110

Functions in C

Functions
● A function is a block of codes or sub programs with a set of statements that perform
some specific task or coherent task when it is called by other functions including
main
● Any ‘C’ program contain at least one function i.e main().
● There are basically two types of functions:
1. Library function
2. User defined function
● The user defined functions defined by the user according to its requirement.
● Library defined function can’t be modified, it can only read and can be used. These
function are supplied with every C compiler

2
What is a Function

A function is a block of statements are used to perform a


specific task.

Every C program has at least one function main( ).

Without main() function, there is technically no C program.


Functions
● Every Function has three parts
● Function Declaration
● Function Definition
● Function Call

4
Function declaration
● Function declaration is also known as function prototype.
● It informs the compiler about three things-
1.name of the function
2.number and type of arguments received by the function
3.the type of value returned by the function.
● While declaring the name of the argument is optional and the function prototype
always terminated by the semicolon.

5
Function Call
● When the function gets called by the calling function then that is - function call.
● The arguments that are used inside the function call are called actual arguments/
parameters and these are the original values and copy of these are actually sent to
the called function
● Example:-
result = add3num(n1,n2,n3); //actual arguments – n1,n2,n3

6
Function definition
● Function definition consists of the code of the function - what function is doing what are
its inputs and what are its output
● Syntax:-
Return_value_Datatype function_name(datatype1 arg1, datatype2 arg2, …) /*function
header*/
{
Local variable declaration;
Statement (s); /* function body */
return (value);
}
● The return_value_Datatype denotes the datatype of the value that function returns
● The arguments in the function definition are known as formal arguments/parameters
● The body of the function is the statements or block which consists of local variable
declaration, one or more executable statements and optional return statement. 7
User Defined Functions arguments list

● Example:
Return_type function_name(datatype 1 arg 1, datatype2 arg2, …)

int add3num(int a, int b, int c)


● Function declaration - int add3num(int, int, int); {
int sum;
● Function definition - complete function code sum = a+b+c;
return sum;
}

● Function call - where the function is used void main() /* calling function*/
{
int n1, n2, n3, result;
printf(“…”);
scanf(“…”);
result = add3num(n1,n2,n3);
printf(“…”);
}
8
Return Statement
● It is used to return a value to the calling function.
● Not more than one value can be returned through the return statement.
● It can be used as return value or return(expression);
● Ex:-
return;
return (a); or return a;
return (a*b+c/d);
return (add3num(a,b,c));
return a,b; invalid
● Here the 1st return statement is used to terminate the function without returning any
value
● We can use a function call statement in the return statement
9
Parameters/Arguments
● Actual arguments
● The arguments which are mentioned or used inside the function call is knows as actual argument and
these are the original values
● It can be written as variable, constant, expression or any function call like
Functionname (x);
Functionname (x, 20, 30);
Functionname (a*b, 15, a, c*d);
Functionname(2, d, sum(a, b));

● Formal Arguments
● The arguments that are mentioned in function definition are called formal arguments or dummy
arguments , that just hold the copies of the actual parameter values that are sent by the calling function
through the function call.
● These arguments are like other local variables which are created when the function call starts and
destroyed when the function ends.
● Order number and type of actual arguments in the function call should be match with the order number10
and type of the formal arguments.
# include<stdio.h>
int add3num(int, int, int); // Optional – Prototype – FUNCTION DELARACTION
void main( ) // Calling Function
{
int n1, n2, n3, result; Actual parameters n1, n2, n3
printf(“Enter 3 numbers”); n1 =
20
scanf(“%d%d%d”, &n1, &n2, &n3);
result = add3num(n1,n2,n3); // FUNCTION CALL n2 =
25
printf(“Sum of 3 numbers = %d”, result);
} n3 =
14

int add3num(int a, int b, int c) // FUNCTION DEFINITION – Called Function


a = 20
{
b = 25
int sum;
sum = a+b+c; // formal parameters a,b,c c = 14 11
Advantages of function

● By using function large and difficult program can be divided in to sub programs
● and solved.
● When some task has to be performed repeatedly or some code is to be used more
than once at different place in the program, then function avoids this repetition or
rewritten over and over.
● Due to reducing size, modular function is easy to modify and test
● Identifying and Debugging errors is easier and faster
● A function can be called any number of times.
● A function can call itself again and again and this process is called recursion.
● A function can be called from other function but a function can’t be defined in
another function
12
Types of Functions
● Functions are categorized based on the argument passing and return value
1. Passing parameter and return value
2. Passing parameter and No return value
3. No passing parameter and return value
4. No passing parameter and No return value
void main() void main() void main() void main()
{ { { {
int n1, n2, n3, result; int n1, n2, n3, result; …….. ……..
printf(“…”); printf(“…”); result = add3num( ); add3num();
scanf(“…”); scanf(“…”); …….. ……..
result = add3num(n1,n2,n3); add3num(n1,n2,n3); } }
printf(“…”); }
}
int add3num( ) void add3num()
void add3num(int a, int b, int c) { {
int add3num(int a, int b, int c) { int a,b,c ,sum; int a,b,c ,sum;
{ int sum; printf(“…”); printf(“…”);
int sum; sum = a+b+c; scanf(“…”); scanf(“…”);
sum = a+b+c; printf(“…”); sum = a+b+c; sum = a+b+c;
return sum; return; return sum; printf(“…”);
} } } return ;
}

14
Passing parameters to functions
● There are two way through which we can pass the arguments/parameters to the
function
● call by value
● call by reference

15
Call by value
● In the call by value copy of the actual argument is passed to the formal argument
and the operation is done on formal argument.
● When the function is called by ‘call by value’ method, it doesn’t change the value of
the actual argument.
● Changes made to formal argument are local inside the called function, so when the
return statement is executed the formal parameters are deleted or terminated in
memory.
void main() /* calling function*/ n1 = a = 20 21
{ 20 int add3num(int a, int b, int c)
int n1, n2, n3, result; {
printf(“…”); int sum; b = 25 26
scanf(“…”); n2 = sum = a+b+c;
a++; b++; c++;
result = add3num(n1,n2,n3); 25 return sum; c = 14 15
printf(“…”);
} }
n3 = Sum = 59
14
16
Call by Reference
● Instead of passing the value of variable, address/ reference is passed and the
function operates on the contents of that address.
● Any changes made to formal argument is reflected on the actual argument, as both
are referring to the same location.

void main() /* calling function*/


{ int add3num(int a, int b, int c)
int n1, n2, n3, result; n1, a = 20 21 {
printf(“…”); int sum;
scanf(“…”); sum = a+b+c; Sum = 59
result = add3num(&n1,&n2,&n3); n2, b = 25 26 a++; b++; c++;
printf(“…”); return sum;
} }
n3, c = 14 15
17
Importance of scope
● Scopes matter for several reasons:
○ Code in the global scope cannot use any local variables.
○ A local scope can access global variables.
○ Code in a function’s local scope cannot use variables in any other local scope.
○ Same name for different variables can be used if they are in different scopes.
○ That is, there can be a local variable named spam and a global variable also named spam.

18
Scope of Variables ● Variables can be either local or global

Global Scope Local Scope


• There is only one global scope, • A local scope is created whenever a
and it is created when the function is called.
program begins. • Any variables assigned in this function
exist within the local scope.
• When the program terminates,
the global scope is destroyed, • When the function returns, the local
scope is destroyed, and these variables
and all its variables are are forgotten.
forgotten.
• The next time you call this function,
the local variables will be created
again with new value.
19
Local and Global Scope
● Parameters and variables that are assigned in a called function are said to
exist in that function’s local scope.
● Variables that are assigned outside all functions are said to exist in the
global scope.
● A variable that exists in a local scope is called a local variable, while a
variable that exists in the global scope is called a global variable.
● A variable must be either local or global; it cannot be both.

20
#include <stdio.h> result = 0 59
int result=0;
void main() /* calling function*/
{
int a, b, c; a = 20
printf(“…”);
b = 25
scanf(“…”);
result = add3num(a,b,c); c = 14
printf(“…”);
}

void add3num(int a, int b, int c) a = 20 21


{
result = a+b+c; b = 25 26
a++; b++; c++;
return; c = 14 15
} 21
Function is basically a set of statements that takes inputs perform some operation and produce output

Syntax: Return_type Function_name(Set_of_inputs);

Return type indicates the type of output returned by the function


Function_name indicates the name of the function
And set of inputs indicates the inputs provided to the function
# include<stdio.h>
int add3num(int, int, int); // Optional – Prototype – FUNCTION DELARACTION
void main( ) // Calling Function
{
int n1, n2, n3, result; Actual parameters n1, n2, n3
printf(“Enter 3 numbers”); n1 =
20
scanf(“%d%d%d”, &n1, &n2, &n3);
result = add3num(n1,n2,n3); // FUNCTION CALL n2 =
25
printf(“Sum of 3 numbers = %d”, result);
} n3 =
14

int add3num(int a, int b, int c) // FUNCTION DEFINITION – Called Function


a = 20
{
b = 25
int sum;
sum = a+b+c; // formal parameters a,b,c c = 14 24
Example:
Suppose we have a task that is always performed exactly in the same way—say a
bimonthly servicing of your motorbike.

When you want it to be done, you go to the service station and say, “It’s time, do it now”.

You don’t need to give instructions, because the mechanic knows his job. You don’t need
to be told when the job is done.

You assume the bike would be serviced in the usual way, the mechanic does it and that’s
that.
Any C program contains at least one function.

If a program contains only one function, it must be main( ).

If a C program contains more than one function, then one (and only one) of these
functions must be main( ), because program execution always begins with main( ).

There is no limit on the number of functions that might be present in a C program.

Each function in a program is called in the sequence specified by the function calls in
main( ).

After each function has done its thing, control returns to main( ).

When main( ) runs out of function calls, the program ends.


1. Built in functions:

The built-in-function are also called library function or Standard Function. These
functions are provided by programmer.

• They are written in the header files.

• To use them appropriate header files should be included.

printf(); and scanf(); are Some common types of built-in-Functions.


1. User defined functions :
Defined by user at the time of writing the program.
User set these program for her own uses.
Written by the programmer at the time of programming.
Add(); Max(); etc are some kinds of user- defined functions.
C allows programmer to define their own function according to
their requirement. These types of functions are known as user-
defined functions.

Suppose, a programmer wants to find factorial of a number and


check whether it is prime or not in same program.

Then, he can create two separate user-defined functions in


that program:

one for finding factorial and

other for checking whether it is prime or not
ADVANTAGES OF USER DEFINED FUNCTIONS

1) User defined functions helps to decompose the large program


into small segments which makes
programmer easy to understand, maintain and debug.

2) If repeated code occurs in a program. Function can be used to


include those codes and execute
when needed by calling that function.

3) Programmer working on large project can divide the workload by


making different functions
Function prototype

Function prototypes Provides the compiler with the description of functions that will be used later in
the program
Its define the function before it been used/called
Function prototypes need to be written at the beginning of the program.
The function prototype must have:
A return type indicating the variable that the function will be return
Syntax for Function Prototype
return-type function_name(arg-type name-1, ,arg-type name-n);
Function definition

It is the actual function that contains the code that will be


execute.
Should be identical to the function prototype.
Syntax of Function Definition
return-type function_name(arg-type name-1,...,arg-type name-n) --- Function header
{
declarations;
Statements; Function Body
return(expression);
}
Examples of function prototypes
double squared(double number);

void print_report(int report_number);

int get_menu_choice(void);
Function return types Can be any of C's data type:
char
int
float
long.
Examples:
int func1(...) /* Returns a type int. */

float func2(...) /* Returns a type float.

void func3(...) /* Returns nothing.


ACTUAL AND FORMAL ARGUMENTS

Argument (or parameter) refers to data that is passed to function (function


definition) while calling function.

Arguments listed in function calling statements are referred to as actual arguments.


These actual values are passed to a function to compute a value or to perform a
task.

The arguments used in the function declaration are referred as formal arguments.
They are simply formal variables that accept or receive the values supplied by the
calling function.

The number of actual and formal arguments and their data types should be same
Example:

Program to add two integers.


Make a function and add integers and display sum in main() function.
Function returns biggest of two integers
Function to return even or odd
Function call
scope OF VARIABLES
● In C, all constants and variables have a defined scope.
● By scope we mean the accessibility and visibility of the variables at
different points in the program.
● A variable or a constant in C has four types of scope;
 block
 function
 program
 file .
Block Scope

// block cope
Function Scope/Local variable
Program Scope/Global variable

● Lifetime Global variables are created at the beginning of program


execution and remain in existence throughout the period of execution of
the program.
● Place of Declaration The global variables are declared outside all the
functions including main().
● Name Conflict If we have a variable declared in a function that has same
name as that of the global variable, then the function will use the local
variable declared within it and ignore the global variable.
// Global variable
File Scope /Global variable
● When a global variable is accessible until the end of the file, the variable is
said to have file scope.
● To allow variable to have 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 is not accessible by any other file.
● Such variables are useful when the programmer writes his own
header files.
Storage Classes

● Storage class defines the scope (visibility) and lifetime of variables and/or
functions declared within a C program.
● The storage class of a function or a variable determines the part of memory
where storage space will be allocated for that variable or function.
● It specifies how long the storage allocation will continue to exist for that
function or variable.
● It specifies whether the variable will be automatically initialized to zero or to
any indeterminate value.
● C supports four storage classes: automatic, register, external, and static.
1. auto

● This is the default storage class for


all the variables declared inside a
function or a block.

● Hence, the keyword auto is rarely


used while writing programs in C
language. Auto variables can be
only accessed within the
block/function they have been
declared and not outside them
(which defines their scope).
2. extern

● Extern storage class simply tells us that the variable is defined elsewhere
and not within the same block where it is used. Basically, the value is
assigned to it in a different block and this can be overwritten/changed in a
different block as well.
● So an extern variable is nothing but a global variable initialized with a
legal value where it is declared in order to be used elsewhere. It can be
accessed within any function/block.
● Also, a normal global variable can be made extern as well by placing the
‘extern’ keyword before its declaration/definition in any function/block.
File1.c File2.c
3. register

● When a variable is declared using register as its storage it is stored in a


CPU register instead of RAM.
● Since the variable is stored in a register, the maximum size of the variable
is equal to the register size.
● One drawback of using a register variable is that they cannot be operated
using the unary ‘&' operator because it does not have a memory location
associated with it.

register int x;
4. static
● The difference between an auto variable and a static variable is that the static
variable when defined within a function is not re-initialized when the function is
called again and again.
● It is initialized just once and further calls of the function share the value of the static
variable. Hence, the static variable inside a function retains its value during various
calls.
static int x = 10;
Static storage class
Comparison of storage classes
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.
● Every recursive solution has two major cases.
●Base case
●Recursive case
To calculate n!
● For the factorial function
● Base case is when n = 1, because if n= 1, the result will be ‘1’ as
1! = 1.
● Recursive case of the factorial function will call itself but with a smaller
value of n, this case can be given as
factorial(n) =n * factorial(n — 1)
Factorial
program
From the aforegiven example, let us analyse the basic steps
of a recursive program.

● Step 1: Specify the base case which will stop the function from making a
call to itself
● Step 2: Check to see whether the current value being processed matches
with the value of the base case. If yes, process and return the value
● Step 3: Divide the problem into smaller or simpler sub problems.
● Step 4: Call the function from the sub-problems.
● Step 5: Combine the results of the sub-problems.
● Step 6: Return the result of the entire problem
Greatest Common Divisor

● GCD(a, b) = | b, if b divides a GCD(a, b)


| GCD (b, a mod b), otherwise
Working
Assume 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
Return 2
Return 2
Programs to be executed.

● Write a program to calculate GCD using recursive functions.


● Write a program to calculate exp(x,y) using recursive functions (Finding
exponent).
● Write a program to print the Fibonacci series using recursion.
#include<stdio.h>
FUNCTION PROTOTYPE
void sum();

void main()

sum(); FUNCTION CALL

void sum() FUNCTION DEFINITION

int a, b;

printf("Enter the two integers:");

scanf("%d%d", &a,&b);

printf("The sum of the numbers you entered is %d",a+b);

}
#include<stdio.h>

void sum(int a,int b);

void main()

int a,b;

printf("Enter the two integers");

scanf("%d%d", &a,&b);

sum(a, b);

void sum(int a, int b)

printf("The sum of the numbers you entered is %d",a+b);

You might also like