Unit Iv: Sumit Sar Department of Computer Science & Engineering BIT, Durg
Unit Iv: Sumit Sar Department of Computer Science & Engineering BIT, Durg
UNIT IV
USER DEFINED FUNCTIONS
Overview
Part I Function Part II Structure
4.1 Syntax of function 4.10 Declaration and initialization of structures
4.2 Calling functions 4.11 Array of structures
4.3 Actual & Formal arguments 4.12 Array within structure
4.4 Categories of function 4.13 structure within structure
4.5 Function prototype 4.14 structure and functions
4.6 Scope rules 4.15 Introduction to Unions
4.6.1 Local & Global variables
4.7 Recursion
4.8 Passing arguments
4.8.1 Call by value
4.8.2 Call by reference
4.9 Passing array to function
Part I Function
Introduction:
A computer program cannot handle all the tasks by it self. Instead its requests other program like entities - called
'functions in C - to get its tasks done. A function is a self contained block of statements that perform a coherent
task of some kind.
e.g
#include <stdio.h>
message();
{
printf ("\n Hello ");
}
main ( )
{
message ( )
printf ("\n I am in main ");
}
*------output of the program will be --------*
Hello
I am in main
Here main ( ) is the calling function and message is the called function. When the function message ( ) is called the
activity of main ( ) is temporarily suspended while the message ( ) function wakes up and goes to work. When the
message ( ) function runs out of statements to execute, the control returns to main ( ), which comes to life again
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
-2-
and begins executing its code at the exact point where it left off.
There are basically two types of functions
{
Statement 1;
statement2; Function body
statement3;
statement4;
}
Formal Arguments:
The arguments specify in function header is called as formal arguments because they represent the names of data
items that are transferred in to the function from the calling portion of the program. They are also called as formal
parameters
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
-3-
Actual Arguments:
The arguments specify in function call is called as actual arguments. Since they define the data items that are
actually transferred. They are also called as actual parameters or simply arguments
Example:
main ( )
{
int a, b, c;
printf ("\n Enter two number");
scanf ("\%d %d ", &a ,&b);
Actual arguments
{
int z;
z = x +y;
return (z);
}
Example:
main ( )
{
add ();
}
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
-4-
Add ()
{
int a, b, c;
printf ("\n Enter two numbers");
scanf ("\%d %d ", &a, &b);
c = a +b;
printf (“The addition of two no is %d”,c)
return (0);
}
Example:
main ( )
{
int a, b;
printf ("\n Enter two number");
scanf ("\%d %d ", &a ,&b);
add (a, b);
}
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
-5-
main ( )
{
int a;
a = add ();
printf(“The addition of two no is %d ”,a);
}
Add ()
{
int a, b,c;
printf ("\n Enter two numbers");
scanf ("\%d %d ", &a ,&b);
c = a +b;
return (c);
}
Example:
main ( )
{
int a, b,c;
printf ("\n Enter two numbers");
scanf ("\%d %d ", &a ,&b);
c = add (a,b);
printf(“The addition of two no is %d ”,c);
}
Add (int x, int y)
{
int z;
z = x +y;
return (z);
}
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
-6-
main ( )
{
float a,b,
printf ("\n Enter any number");
scanf ("\% f", &a );
b = square (a);
printf ("\n square of % f is % f", a,b);
}
square (Float x)
{
float y;
y = x * x;
return (y);
}
*-------Output of this program ------------*
Enter any number 2.5
square of 2.5 is 6.000000
Here 6 is not a square of 2.5.The reason is any C function by default always returns an integer value
main ( )
{
float square ( );
float a, b;
printf ("\n Enter any number ");
scanf ("%f" &a);
b = square (a);
printf ("\n square of % f is % f, " a, b);
}
float square (float x)
{
float y;
y= x *x;
return ( y);
}
*------------------Output----------------------*
Enter any number 2.5
Square of 2.5 is 6.2500000
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
-7-
4.6 Scope rules
4.6.1 Local & Global variables
Local
A local variable is a variable that is given local scope. Such variables are accessible only from the function or block
in which it is declared. Local variables are contrasted with global variables. Local variables are special because in
most languages they are automatic variables stored on the call stack directly. This means that when a recursive
function calls itself, local variables in each instance of the function are given separate memory address space.
Hence variables of this scope can be declared, written to, and read, without any risk of side-effects to processes
outside of the block in which they are declared.
Global
These variables can be accessed (i.e. known) by any function comprising the program. They are implemented by
associating memory locations with variable names. They do not get recreated if the function is recalled.Global
variables are used extensively to pass information between sections of code that don't share a caller/callee relation
like concurrent threads and signal handlers.
#include <stdio.h>
int global = 3; // This is the global variable.
void ChangeGlobal()
{
global = 5; // Reference to global variable in a function.
}
int main()
{
Printf (“%d ”, global); // Reference to global variable in another function.
ChangeGlobal ();
Printf (“ %d ”, global);
return 0;
}
*-----------------Output-----------------*
3 5
4.7 Recursion
Recursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied.
The recursion is used for repetitive computations
Let us take an example
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
-8-
main ( )
{
int a,b;
printf ("\n Enter any number ");
scanf ("%d" &a);
b = Factorial (a);
printf ("\n Factorial of % d is %d, " a, b);
}
Factorial (int n)
{
Int Fact;
If(n==1)
{
return (1);
}
Fact=n * Factorial(n-1);
return ( Fact);
}
The advantage of using recursive functions, may not be obvious at first sight, there are situations, when a recursive
function reduces the complexity of program writing significantly.
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
-9-
} /* end of fibonacci() */
OUTPUT:
Enter no.of entries: 9
The fibonacci series:
1
1
2
3
5
8
13
21
34
/* program to calculate the GCD of two numbers */
#include <stdio.h>
#include<math.h>
unsigned gcd(unsigned num1,unsigned num2);
main()
{
unsigned num1,num2;
printf(“Enter two numbers whose GCD is to be found:”);
scanf(“%u %u”, &num1, &num2);
printf(“GCD of %u and %u is = %u\n”,num1,num2,gcd(num1,num2));
}
unsigned gcd(unsigned num1, unsigned num2) /* Function to calculate the GCD of two unsigned numbers */
{
unsigned num, gcdnum,i;
num = num1 < num2 ? num1:nim2;
for (i =1; i<=num; i++)
if ((num1% i == 0) && (num2 % i ==0))
gcdnum = i;
return gcdnum;
}
OUTPUT:
Enter two numbers whose GCD is to be found: 25 10
GCD of 25 and 10 is = 5
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
- 10 -
In this method the value of each of the actual arguments in the calling function is copied into corresponding formal
arguments of the called function. With this method the changes made to the formal arguments in the called
function have no effect on the values of actual argument in the calling function. The following program illustrates
this
main ( )
{
int a = 10, b=20;
swapy (a,b);
printf ("\na = % d b = % d", a,b);
}
swapy (int x, int y)
{
int t;
t = x;
x = y;
y = t;
printf ( "\n x = % d y = % d" , x, y);
}
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
- 11 -
a =10 b =20
In the second method the addresses of actual arguments in the calling function are copied in to formal arguments
of the called function. This means that using these addresses we would have an access to the actual arguments and
hence we would be able to manipulate them. The following program illustrates this.
main ( )
{
int a = 10, b =20,
swapr (&a, &b);
printf ("\n a = %d b= %d", a, b);
}
swapr (int *x, int * y)
{
int t;
t = *x
*x = *y;
*y = t;
}
The output of the above program would be
a = 20 b =10
main()
{
int a[5]={1,3,5,7,9},i;
clrscr();
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
- 12 -
for(i=0;i<5;i++)
{
Funval(a[i]);
}
}
Funval (int g)
{
Printf(“ %d ”, g);
}
main()
{
int a[5]={1,3,5,7,9},i;
clrscr ();
Funval (&a);
}
First way
#include<conio.h>
#include<stdio.h>
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
- 13 -
main()
{
int a[3][3]={1,3,5,7,9,11,13,15,17},i;
clrscr ();
Funval (&a);
}
Second way
#include<conio.h>
#include<stdio.h>
main()
{
int a[3][3]={1,3,5,7,9,11,13,15,17},i;
clrscr ();
Funval (&a);
}
Third way
#include<conio.h>
#include<stdio.h>
main()
{
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
- 14 -
int a[3][3]={1,3,5,7,9,11,13,15,17},i;
clrscr ();
Funval (&a);
}
3. A function is defined when function name is followed by a pair of braces in which one or more statements may
be present for e.g.
message ( )
{
statement 1;
statement2;
statement 3;
}
4. Any function can be called from any other function even main ( ) can be called from other functions for e.g.
main ( )
{
message ( );
}
message ( )
{
printf (" \n Hello");
main ( );
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
- 15 -
}
8. A function can be called from other function, but a function cannot be defined in another function. Thus the
following program code would be wrong, since Argentina is being defined inside another function main ( ).
main ( )
{
printf ("\n I am in main");
Argentina ( )
{
printf {"\n I am in Argentina");
}
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
- 16 -
}
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
- 17 -
Part II Structure
4.10 Declaration and initialization of structures
We have learnt to create group elements of the same type into a single logical entity- array. If it looks like a
jargon, consider this, the variables are being put in a group, they are referred by a single name - and importantly
they were all of the same type. Either all were integers, all floats etc.. what if we want to group different types of
items into one logical entity say day, month and year to be called the date? Further what if we want to group these
elements into bigger entities?
Consider the following example: every date is made up of 3 parts day, month and year. Day is an integer;
month is a string of character and year an integer. Now suppose, we want to declare date of birth, date of joining
service, date of marriage etc... Each of them is similar to the variable date - each having a day which is an integer,
a month which is a string of character and year, an integer.
C provides a nice way of declaring and managing such situations. It makes use of a concept called
structure.
Syntax:
Struct tag name Tag name is optional
{
Data type member1;
Data type member2;
Data type member3;
…
}
Struct date
{
int day;
char month[3];
int year;
};
This means date is a structure - it has 3 parts - an integer called day, a character string of 3 elements
called month and another integer called year.
Now we can declare date of birth as a structure of the type date structure date date_of_birth.
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
- 18 -
We use date_of_birth .year
And so on.
We can use these as if they are variable names. A few examples will clarify their usage.
/* program to illustrate a structure */
main()
{
struct date
{
int month;
int day;
int year;
};
struct date today; // Structure variable declaration
OUTPUT:
Today's date is 9/12/1981.
Initialization of structures
First variation
/* The following program is to illustrate a initialization of structure */
main()
{
struct date
{
int month;
int day;
int year;
};
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
- 19 -
struct date today={9,12,1981}; // Structure variable declaration + Initialization
printf ("Today's date is %d/%d/%d\n", today.month,today.day,today.year %100);
}
OUTPUT:
Today's date is 9/12/1981.
Second variation
/* The following program is to illustrate a initialization of structure */
main()
{
struct date
{
int month;
int day;
int year;
} today= {9, 12, 1981};
printf ("Today's date is %d/%d/%d\n", today.month,today.day,today.year %100);
}
OUTPUT:
Today's date is 9/12/1981.
Third variation
/* The following program is to illustrate a initialization of structure */
struct date
{
int month;
int day;
int year;
};
main()
{
struct date today={9,12,1981}; // Structure variable declaration + Initialization
printf ("Today's date is %d/%d/%d\n", today.month,today.day,today.year %100);
}
OUTPUT:
Today's date is 9/12/1981.
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
- 20 -
Let us take an example
struct marks
{
int C_Prog;
int Digital;
int Maths;
};
main ()
{
struct marks student[10]={{45,46,42},{34,39,41}};
}
This declares the student as an array of 10 elements and we initialize only subject marks of two students i.e.
student [0] and student [1]
struct marks
{
int C_Prog;
int Digital;
int Maths;
};
main ()
{
struct marks student[10]={{45,46,42},{34,39,41}};
}
This declares the student as an array of 10 elements and we initialize only subject marks of two students i.e.
student [0] and student [1]
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
info - 21 -
Struct info
{
rollno
int rollno;
char name[30]; name
struct marks
marks
{
int c_prog;
int digital; C_prog
int maths;
digital
}subject;
}student[10]; maths
main ()
{
Student [0].subject.c_prog=44;
Student [0].subject. digital=32;
Student [0].subject.maths=49;
printf (“%d %d %d”, Student [0].subject.c_prog, Student [0].subject. digital, Student [0].subject.maths)
}
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
- 22 -
In call by reference we pass the entire structure to the function i.e. we pass the address of the structure
variable to the function
For example
Struct info
{
int rollno;
char name [10];
};
main ()
{
int a,b,c;
struct info student={22,”ravi”};
fun (&student);
}
union date
{
int day;
char month[3];
int year;
};
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
- 23 -
Syntax for declaration of union variable:
Storage class Union tag name variable 1, variable 2…;
An individual union member can be accessed in the same manner as an individual structure member.
For ordinary union variable
union variable . Member
For pointer structure variable
union variable -> member
union info
{ Stud1.f
Int a;
Char c;
Float f;
} stud1; 800 801 802 803
Stud 1.a
Stud1.c
Sumit Sar
Department of Computer Science & Engineering
BIT, Durg