UNIT-3: Functions and Structures

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 51

UNIT-3

FUNCTIONS AND
STRUCTURES

SYLLABUS
Functions: Introduction, Function
Definition, Function Declaration, Return
values and their Types, Function Calls,
Categories of Functions, nesting of
Functions, Recursion, Passing arrays to
Functions, Storage Classes.
Structure: Basics of Structures,
Structures to Functions, Arrays of
Structures, Structures with in Structures,
Arrays with in structures, Unions.

WHY TO GO FOR
FUNCTIONS?
Just think of printf(), scanf(), main(),
getch()..
etc which you have used so far

What are they called?


How does they help us?

NEED FOR FUNCTIONS


To obtain structured programming we
choose functions.
They give modularity to programs
Makes our job easy.
Readability increases
Divide and conquer
Construct a program from smaller pieces or
components
These smaller pieces are called modules

Each piece more manageable than the original


program

DEFINITION OF A
FUNCTION
A function is a
self contained
block of code
that performs
a specific task.
Fig: Top-Down
Modular
Programming using
functions

TYPES OF FUNCTIONS
C

functions can be classified into two


categories...
Standard Library Functions
&
User Defined Functions

ADVANTAGES OF A
FUNCTIONS
Benefits of functions
Divide and conquer
Manageable program development

Software reusability
Use existing functions as building blocks for
new programs
Abstraction - hide internal details (library
functions)

Avoid code repetition


Debugging becomes easy
Length of code decreases

STANDARD LIBRARY
FUNCTIONS
C provides a set of library functions
defined in standard libraries.
They have a pre-defined code
They can just be used where ever
needed by just including the library
in which they are present and
writing or calling it with needed
inputs or parameters.

Examples.....!!

printf(),scanf(),strcat(),strcmp(),
strcpy(),strlen(),strstr(),getch(),
getchar(),gets(),
puts(),getche(),putchar() etc..

USER DEFINED
FUNCTIONS
A user can create their own functions for performing

any specific task of program are called user defined


functions.
This function code has to be developed by the user
at the time of writing a program.
Eg: main()
main is specially used function in C.
Every program must have main function to indicate,
where the program begins its execution.
When a program is too large and complex then the
result of debugging testing and maintaining becomes
difficult.
so functions makes our job easy

ELEMENTS OF A USER
DEFINED FUNCTION
To create and use these functions, we
have to know these 3 elements.
Function Declaration
Function Definition
Function Call

FUNCTION DECLARATION
The function that calls a function is
referred to as the calling function.
The calling program should declare any
function that is to be used later in the
program this is known as the function
declaration or function prototype.
Syntax:
function
prototype

return-value-type
function_name( parameter-list );

eg: int sum(int,int);


void print_message(void);

Function name:
This is the name given to the function. It
follows the same naming convention as that
of any valid variable in C.
Return data type:
This specifies the type of data given back to
the calling construct.
Data type list:
This list specifies the data type of each
variables, the values of which are expected
to be transmitted to the function. These
variables are known as formal parameters.

FUNCTION DEFINITION
The function definition consists of the whole description
and code of a function. It tells that what the function is
doing and what are the input outputs for that.
Function definitions have two parts:
Function Header
Function Body
The first line of the definition is called Function Header.
It has three parts
(i). The name of the function i.e. sum
(ii). The parameters of the function enclosed in parenthesis
(iii). Return value type i.e. int
eg:

int sum( int x, int y)

The Function Body:


Whatever is written with in { } is the body
of the function.
Syntax:
return-value-type
function_name( parameter-list )
//function header
{
<local variable declarations;> //function
body
<executable statements;>
<executable statements;>
<return statement;>
}
//function close

FUNCTION CALL
In order to use the function we need to
invoke it at a required place in the program.
This is known as the function call.
A function is called by simply writing the
name of the function followed by the
argument list inside the parenthesis.
Syntax:

function_name( parameters);
//if no return type
return_type variable=
function_name( parameters);
// if return type exists

FUNCTION PROTOTYPE &


HEADER
Only difference is a semicolon
Function header:
return-value-type
function_name( parameter-list )

Function prototype:
return-value-type
function_name( parameter-list );

ARGUMENTS & PARAMETERS


A parameter is the variable which is part of the
method's signature (prototype & declaration).
An argument is an expression used when
calling the method.
Consider the following code
void Foo(int i, float f)
{
// Do things
}
void Bar()
{
int anInt = 1;
Foo(anInt, 2.0);
}
Hereiandfare the parameters, andanIntand2.0are the
arguments

FORMAL PARAMETERS &


ACTUAL PARAMETERS
Arguments/Actual Parameters:
These are the parameters , given during a
function call to the called function in
the calling function (usually main())
Parameters/Formal Parameters/Dummy
Parameters:
These are the parameters,in the
function definition to which a copy of
the values are transferred into .

CALLING FUNCTIONS: CALL BY


VALUE AND CALL BY REFERENCE
Used when invoking functions
Call by value
Copy of argument passed to function
Changes in function do not effect original
Use when function does not need to modify
argument
Avoids accidental changes

Call by reference
Passes original argument
Changes in function effect original
Only used with trusted functions

PASS BY VALUE (OR) CALL BY VALUE :In this method calling function sends a copy of actual values to called function, but
the changes in called function does not reflect the original values of calling
function.
Example program:
#include<stdio.h>
void fun1(int,int);
void main( )
{
int a=10, b=15;
fun1(a,b);
printf(a=%d,b=%d, a,b);
getch():
}
void fun1(int x, int y)
{
x=x+10;
y= y+20;
}
Output: a=10 b=15
The result clearly shown that the called function does not reflect the original values
in main function.

PASS BY REFERENCE (OR) CALL BY REFERENCE :In this method calling function sends address of actual values as a
parameter to called function, called function performs its task and
sends the result back to calling function.
Example program:
#include<stdio.h>
void fun1(int,int);
void main( )
{
int a=10, b=15;
fun1(&a,&b);
printf(a=%d,b=%d, a,b); getch(): }
void fun1(int *x, int *y)
{
*x = *x + 10;
*y = *y + 20;
}
Output: a=20 b=35
The result clearly shown that the called function reflect the original
values in main function. So that it changes original values.

RETURN VALUES/RETURN TYPES


it is the type of the values the function is expected to
return back to the calling function, if nothing then void

CATEGORIES OF
FUNCTIONS
A function depending on whether arguments are
present or not and whether a value is returned or
not may belong to any one of the following
categories:
(i ) Functions with no arguments and no return
values.
(ii) Functions with arguments and no return
values.
(iii) Functions with arguments and return values.
(iv) Functions with no arguments and return
values.

I:FUNCTION WITH NO ARGUMENTS


AND NO RETURN VALUES
When a function has no arguments, it does
not take any data from calling
functionduring function call no arguments
are given.
When a function does not return a value,
the calling function does not receive any
data from the called function which does
not have a return statement.
That is there is no data transfer between
the calling function and the called function.

Example: no arguments & no return value

Program:
#include <stdio.h>
#include <conio.h>
void printmsg(void)
{
printf ("Hello ! I Am A
Function .");
}
int main()
{
printmsg();
return 0;
};
Output : Hello ! I Am A
Function .

II: FUNCTION WITH ARGUMENTS


AND NO RETURN VALUES
When a function has arguments data is
transferred from calling function to called
function i.e during the function call values are
given.
The called function receives data from calling
function and does not send back any values to
calling function.
Because it doesnt have return value.
That is there is only one way data transfer
between the calling function to the called
function and not viceversa.

Example: with arguments & no return values


Program:
#include<stdio.h>
#include <conio.h>
void add(int,int);
void main()
{
int a, b;
printf(enter value);
scanf(%d%d,&a,&b);
add(a,b);
}
void add (intx, inty)
{
int z ;
z=x+y;
printf ("The sum =%d",z);
}
output :
enter values 2 3
The sum = 5

III: FUNCTION WITH NO ARGUMENTS


AND WITH RETURN VALUES
When function has no arguments, data can
not be transferred to called function
through a function call.
But the called function can send some
return values to the calling function by
using a return statement as the last line in
its definition.
That is there is only one way data transfer
between the called function to the calling
function and not vice versa.

Example: no arguments & with return values


Progrram:
#include<stdio.h>
#include <conio.h>
int add( );
void main()
{
int c;
c=add();
printf ("The sum =%d",c);
}
int add ()
{ int x,y,z;
printf(enter value);
scanf(%d%d,&a,&b);
z=x+y;
return z;}
Output:
enter values 2 3
The sum = 5

IV: FUNCTION WITH ARGUMENTS


AND WITH RETURN VALUES
When a function has arguments, it takes
any data from calling function ,during a
function call arguments are given.
When a function has a return a value, the
calling function also receives some data
from the called function which has a return
statement.
That is there is two way data transfer
between the calling function and the called
function.

Example: with arguments & with return values


Example
#include<stdio.h>
#include <conio.h>
int add( int, int);
main()
{
int a,b,c;
printf(enter value);
scanf(%d%d,&a,&b);
c=add(a,b);
printf ("The sum =%d",c);
}
int add (int x, int y)
{
int z;
z=x+y;
return z;
}
output :
enter values 2 3
The sum = 5

NESTING OF FUNCTIONS
The process of calling a
function within another
function is called
nesting of function .
main () can call function
1() where function1
calls function2() which
calls function3() and so
on .
Like this a chain of
function callings to
various functions can
be made and linked
together.

main()
{
..
function1();
.
}
function1();
{

function2();

}
function2();
{

function3();

}
function3();
{ . }

Program to show
nesting of functions:
float ratio (int,int,int);
int difference (int,int);
void main()
{
int a,b,c,d;
printf( enter three
numbers);
scanf(%d%d%d, &a, &b,
&c );
d= ratio(a,b,c);
printf (%f\n ,d);
}
float ratio(int x,int y,int
z);
{

if (u)
return(x/(y-z));
else
return (0.0);
}
int difference (int p,int q)
{
if(p!=q)
return 1;
else
return 0;
}
Explanation:
main reads values a,b,c, and calls
ratio() to calculate a/(b-c) ratio
calls another function difference
to test whether (b-c) is zero or not
this is called nesting of function

RECURSION

Recursion is a process by which a function calls itself


repeatedly, until some specified condition has been
satisfied.
When a function calls itself, a new set of local variables and
parameters are allocated storage on the stack, and the
function code is executed from the top with these new
variables.
A recursive call does not make a new copy of the function.
Only the values being operated upon are new.
As each recursive call returns, the old local variables and
parameters are removed from the stack, and execution
resumes immediately after the recursive call inside the
function.
The main advantage of recursive functions is that we can
use them to create clearer and simpler versions of several
programs.

Syntax:A function is recursive if it can call itself;


either directly (or) indirectly:
void f( ) {f( );}
//direct
void f( ) {g( );} void g( ) {f( );}
//direct
Recursion rule 1: Every recursive method
must have a base case -- a condition under
which no recursive call is made -- to prevent
infinite recursion.
Recursion rule 2: Every recursive method
must make progress toward the base case
to prevent infinite recursion

Program:
#include<stdio.h>
int fact(int);
main()
{
int n,f;
printf(\n Enter any number:);
scanf(%d,&n);
f=fact(n);
printf(\n Factorial of %d is %d,n,f);
}
int fact(int n)
{
int f;
if(n==0||n==1) //base case
f=1;
else
f=n*fact(n-1); //recursive case
return f;
}
Output:- Enter any number: 5
Factorial of 5 is 120

RECURSION VS.
ITERATION
Repetition
Iteration: explicit loop
Recursion: repeated function calls

Termination
Iteration: loop condition fails
Recursion: base case recognized

Both can have infinite loops


Balance
Choice between performance (iteration)
and good software engineering (recursion)

PASSING ARRAYS TO
FUNCTIONS

Passing Array Individual Elements to Functions:

Array element can be passed to a function by calling the


function by value, or by reference. in the call by value, we
pass values of array elements to the function, whereas in
the call by reference, we pass address of array element to
the function. These two calls are illustrated below
The function must be called by passing only the name of
the array.
In the function definition, the formal parameters must be
an array type, the size of the array does not need to be
specified.
The function prototype must show that the argument is an
array.
To process arrays in a large program, we have to be able to
pass them to functions. We can pass arrays in two ways:
pass individual elements or pass the whole array.

Passing Array Individual Elements to Functions:

Passing Entire Array toFunctions:


Passing entire array to function :
Parameter Passing Scheme :Pass by
Reference
Passname of arrayas function
parameter .
Name contains the base address i.e (
Address of 0th element )
Array values are updated in
function .
Values are reflected inside main

STORAGE CLASSES
Variables in C differ in behavior. The behavior
depends on the storage class a variable may
assume
Storage class specifiers in C language tells
the compiler where to store a variable, how
to store the variable, what is the initial value
of the variable and life time of the variable.
There are four storage classes in C:
Automatic storage class
Register storage class
Static storage class
External storage class

Let us now
know about

structures

You might also like