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

Functions in C

Uploaded by

R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Functions in C

Uploaded by

R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Function in C

What is Function in C?
• A set of statements grouped together into a single logical unit is referred to
as Function.
• A function is a self-contained block of code that performs a particular task.
• Example
main()
{
int a,b,c;
c=a+b;
}
• Note: main() is a specially recognized function in C and every C program
must have exactly one main().
Syntax of Functions in C

• The syntax of function can be divided into 3 aspects:


• Function Declaration:In a function declaration, we must provide the
function name, its return type, and the number and type of its parameters.
A function declaration tells the compiler that there is a function with the
given name defined somewhere else in the program.

• Function DefinitionThe function definition consists of actual statements


which are executed when the function is called (i.e. when the program
control comes to the function).
• Function Calls: A function call is a statement that instructs the compiler to
execute the function. We use the function name and parameters in the
function call.
• In a function declaration, we must provide the function name, its
return type, and the number and type of its parameters. A function
declaration tells the compiler that there is a function with the given
name defined somewhere else in the program.
• The function definition consists of actual statements which are
executed when the function is called (i.e. when the program control
comes to the function).
• A function call is a statement that instructs the compiler to execute
the function. We use the function name and parameters in the
function call. In the below example, the first sum function is called
and 10,30 are passed to the sum function. After the function call sum
of a and b is returned and control is also returned back to the main
function of the program.
// C program to show function
Example of C // call and definition
#include <stdio.h>
Function
// Function that takes two parameters
// a and b as inputs and returns
// their sum
int sum(int a, int b)
{
return a + b;
}

// Driver code
int main()
{
// Calling sum function and
// storing its value in add variable
int add = sum(10, 30);

printf("Sum is: %d", add);


return 0;
}
Function Return Type
• Function return type tells what type of value is returned after all
function is executed. When we don’t want to return a value, we can
use the void data type.
• Function Arguments
• Function Arguments (also known as Function Parameters) are the
data that is passed to a function.

The Formal Parameters are the values determined by the function that accepts values when the function is declared.
• Passing Parameters to Functions
• The data passed when the function is being invoked is known as the Actual
parameters. In the below program, 10 and 30 are known as actual parameters.
Formal Parameters are the variable and the data type as mentioned in the
function declaration. In the below program, a and b are known as formal
parameters.
• Conditions of Return Types and Arguments
• In C programming language, functions can be called either with or
without arguments and might return values. They may or might not
return values to the calling functions.
• Function with no arguments and no return value
• Function with no arguments and with return value
• Function with argument and with no return value
• Function with arguments and with return value
How Does C Function Work?
Working of the C function can be broken into the following steps as
mentioned below:
• Declaring a function: Declaring a function is a step where we declare a
function. Here we define the return types and parameters of the function.
• Defining a function:
• Calling the function: Calling the function is a step where we call the
function by passing the arguments in the function.
• Executing the function: Executing the function is a step where we can run
all the statements inside the function to get the final result.
• Returning a value: Returning a value is the step where the calculated value
after the execution of the function is returned. Exiting the function is the
final step where all the allocated memory to the variables, functions, etc is
destroyed before giving full control to the main function.
Interaction between Function Blocks – Categories
based on Arguments & Return Values
• Based on the exchange of arguments and return values between
interacting functions, there may be FOUR categories

CATEGORY Arguments: Data flowing Return: Data being returned


from Calling Function to by Called Function to Calling
Called Function Function

Category 1 NO NO

Category 2 YES NO

Category 3 YES YES

Category 4 NO YES
Example – Display messages from various blocks

void disp(); // function prototype void disp() //function definition


main() {
{ printf(“I am at fun Disp”);
printf(“hello from main”); }
disp(); // invocation Output
printf(“bye from main”); hello from main
} I am at fun Disp
bye from main

Category – 1 (No argument / No Return)


Flow of Arguments between Function Blocks
• It is possible to capture data in one function block and transfer them to other
function blocks whichever are invoked. This phenomenon is called Function Call.

• A function call is an expression that passes control and arguments (if any) to a
function.

• The arguments passed may be absolute value or address.

• Whenever a function is called and arguments passed as values, such invocation is


called as CALL-BY-VALUES.

• Whenever a function is called and arguments passed as addresses, such invocation is


called as CALL-BY-REFERENCE.
• Call By Value in C: In this parameter passing method, values of actual
parameters are copied to function’s formal parameters and the two
types of parameters are stored in different memory locations. So any
changes made inside functions are not reflected in actual parameters
of caller.
• In other words, in this parameter passing method, values of actual
parameters are copied to function's formal parameters, and the
parameters are stored in different memory locations. So any changes
made inside functions are not reflected in actual parameters of the
caller
Flow of Arguments between Function Blocks - Example
Formal Parameter
void sum(int, int); void sum(int x, int y)
main() {
o
x int z;
{ ed
t
Actual
a p p z=x+y;
int a,b; Parameter is m o
y
a e d
t printf(“The Sum =%d”, z);
a=5, b=6; p
ap } Output
m
is The Sum = 11
sum(a,b); b
Bye from main
a=5
printf(“bye from main”); c
b=6 o
} x p
CALL BY VALUE y y

z
Arguments passed but no return value
Flow of Arguments between Function Blocks - Example

sum(int, int); sum(int x, int y)


main() {
{ return (x+y);
int a,b, result;
a=5, b=6; }
result = sum(a,b);
a=5
printf(“The sum is%d”, result); Output c
The Sum = 11 b=6 o
} x p
y y
Arguments passed and value returned back
result
CALL BY VALUE
Function invocation using Call-by-Reference

int compute (int *, int *); int compute (int *p1, int *p2)
{
#include <stdio.h> return (* p1 + * p2);
int main() }
{
int a=5,b=6, z; Output
Result is 11
z=compute(&a, &b);
printf(“Result is%d", z);
Pointers p1 & p2 are
return 0; pointing to a and b
} respectively
Handling Non-Integer Function

float compute(int, int); float compute(int x, int y)


main() {
{
return ((float) (x/y));
int a,b;
}
float result;
Output
a=25, b=7; The result is = 3.5714
result = compute(a,b);
printf(“The result is%f”, result); Default return type of any function is int

} In order to obtain non-integer value,


function must be declared with the data
type
How Call by Value & Call by Reference differ?
mod(int); mod(int *);

main() main()
{ {
A 5
int a=5; int a=5;
mod(a); mod(&a);
X <-- 5
printf(“a is %d”, a); +100=105 printf(“a is %d”, a);
} } A 5+100
mod(int x) 105
{ mod(int *x)
x=x+100; {
printf(“x is %d”, x); *x= *x+100;
} }
*x &a
Call by Reference
Call by Value
Categories of C Functions

Library User Defined


Functions Functions

printf( ) main ( )
scanf() written by the programmer
strlen()
getchar()
--- C allows user to include
--- multiple user defined
functions
How does Multiple Functions Work
Fun ()
main() Arguments
(if any) {
{
---
st-1 Called function
---
St-2
Return values }
St-3: Invoke Fun() (if any)
St-4
St-5
}
Points to Remember
Multiple user defined functions allowed.
Calling function
Any function can invoke any other function and any number of
times
A function can also invoke itself – such are called Recursive
function
A function may send parameters to other function called as
ARGUEMENTS.
A function may perform computation and RETURN back results.
Need for User defined functions
• Enables Modularization of large
complex problems.
• Facilitates top down modular main()
programming.
• Ease of debugging & testing.
• Ease in modifying program. Fun-1 Fun-2 Fun-n
• Repeated use of modules.
• Reduce length of program.
The C Function - Format
• User defined functions must • General Format (function
be given names – The rules definition):
for naming identifier also
holds good for naming
function.
data_type fun_name (argument list)
• General Convention of
{
function declaration is to local variable declaration;
declare a prototype before
main() and at the end of executable statements;
main the function to defined. }
Function invocation using Call-by-Value & Call-by-Reference

float compute(float, float *); float compute(float r1, float *p)


main() {
{ float a;
float r, area, perimeter; a=(float) 3.14*r1*r1;
radius = 4; *p=(float) 2*3.14*r1;
area = compute(r, &perimeter); return a;
printf(“Area=%f, area); }
printf(“Perimeter=%f”, perimeter);
}
Accessing Array using Pointer & Function

void modify(int *); void modify(int *p)


{
#include <stdio.h> int j;
for(j=0;j<5;j++)
void main() {
{ *p = *p+100;
int a[5]={10,20,30,40,50}, i; p++;
modify(a); }
Output
for(i=0;i<5;i++) } 110
printf("%d\n", a[i]); 120
130
} 140
150
Passing Array to a Function

Size not declared

#include <stdio.h> void disp(int b[])


void disp(); app
ed {
m
int main() int i;
{ for(i=0;i<3;i++)
int a[3]={10,20,30}; printf("%d\n", b[i]);
OUTPUT
disp(a); }
10
return 0; 20
30
}
Recursive Function
• A function invoking itself directly or
indirectly is called Recursive Function.
Fun
• A recursive function usually forms a 1
cycle of invokation and therefore
suitable terminal conditions must be Direct Recursion – Self Invocation
placed to break the infinite cycle of
invocation.
• Eg: Fun Fun Fun
myfun() 1 2 N
{
---
myfun(); Indirect Recursion – Invocation through other function
---
}
Recursive Function – When to use
• Whenever a problem can be
redefined in terms of problems
in terms of smaller units which
are corelated.
• The problem thus can be
reduced entirely to simple cases
by calling the recursive function.
• If this is a simple case Recursive splitting of the problem into
solve it a problem of size 1 and another
else problem of size n-1.
redefine the problem using
recursion
Recursive Function – Example
Ch: 5th scan . terminal
// Print Character Backwards void prn()
Ch: 4th scan T Pending to print
{
void prn(); Ch: 3rd scan I Pending to print
char ch;
Ch: 2nd scan M Pending to print
main() scanf(“%c”, &ch); Pending to print
Ch: 1st scan S
{ if( ch!= ‘.’)
printf (“Enter characters and { When terminal achieved, next
type ‘.’ to terminate”); prn(); statement start executing – print
statement: POP operation starts.
prn();
printf(“%c”, ch);
printf(“bye from main”); }
T I M S
} }
Test Case
Input: SMIT. Printed in reverse order
Output: TIMS
Recursive Function – Example contd..

ch ch != ‘.’ Action Pending

T Y prn(); Print T T I M S

I Y prn(); Print I
M Y prn(); Print M Printed in reverse order

S Y prn(); Print S
. N Pop operation
Static Variable Demonstration in Function

•Recall Static Variables are local Variables which retain its


values even after the control jumps out of the function
block.

•On the contrary, an Auto variable does not retain its value.

•Static Variables are used whenever the value of a variable


declared within a function block is required to be retained
irrespective of closure of the function.
Auto Variable Example

#include<stdio.h> int fun()


int fun(); {
int main() int count = 0;
{ count++;
printf("\n%d ", fun()); return count;
printf("\n%d ", fun()); }
return 0;
} Output

1
1
Static Variable Example

#include<stdio.h> int fun()


int fun(); {
int main() static int count = 0;
{ count++;
printf("\n%d ", fun()); return count;
printf("\n%d ", fun()); }
printf("\n%d ", fun());
Output
return 0;
1
}
2
3
Practice Program
• Add an element in the array at the top position
• Delete an element from the array at the top position
• Add an element at the bottom position
• Delete an element from the top position
• Add / Delete an element in ith position – Adjust the elements in the
array.
[0] 102
[0] 102 [0] 102
[1] 76 Del element at pos
[1] 87 [1] 76
[2] 45 [2] value is 76
[2] 45 [2] 87 Add element at pos
[3] 506
[3] 506 [3] 45 [1] value is 76
[4] 0
[4] 506

You might also like