0% found this document useful (0 votes)
77 views23 pages

Unit Iv: Sumit Sar Department of Computer Science & Engineering BIT, Durg

The document discusses user defined functions in C programming. It covers the syntax of functions, different categories of functions based on arguments and return values, function prototypes, scope rules, recursion, passing arguments by value and reference, and passing arrays to functions. It also discusses structures, including declaration and initialization of structures, arrays of structures, arrays within structures, structures within structures, and using structures with functions.

Uploaded by

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

Unit Iv: Sumit Sar Department of Computer Science & Engineering BIT, Durg

The document discusses user defined functions in C programming. It covers the syntax of functions, different categories of functions based on arguments and return values, function prototypes, scope rules, recursion, passing arguments by value and reference, and passing arrays to functions. It also discusses structures, including declaration and initialization of structures, arrays of structures, arrays within structures, structures within structures, and using structures with functions.

Uploaded by

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

-1-

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

1. Library functions e.g printf ( ), scanf ( ) etc


2. User defined function e.g. the function message ( ) mentioned above

4.1 Syntax of function

The General form of a function is


1. Classic method:
Arguments list

function (arg1, arg2, arg3) Function header

type arg1, arg2, arg3 Arguments declarations

{
Statement 1;
statement2; Function body
statement3;
statement4;
}

2. Modern / ANSI method:

function (type arg1,type arg2, type arg3)


{
Statement 1;
statement2;
statement3;
statement4;
}
4.3 Actual & Formal arguments

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

c = add (a, b);


Function Call
printf(“The addition of two no is %d ”,c)
}
Formal arguments

Add (int x, int y)

{
int z;
z = x +y;
return (z);
}

4.4 Categories of function

A Function in C belongs to one of the following categories:


1. Function with no arguments and no return values
2. Function with arguments and no return values
3. Function with no arguments and return values
4. Function with arguments and return values

1. Function with no arguments and no return values


When a function has no actual arguments, it does not receive any data from the calling function. Similarly,
when any function does not return any value, the calling function does not receive any value from the function

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);
}

2. Function with arguments and no return values


In this category a function has arguments, i.e. the function receives data from the calling function. In this
category the actual arguments and formal arguments should match in number, type and order. The values of actual
arguments are assigned to the formal arguments on a one to one basis and it does not return any values to the
calling function

Example:
main ( )
{
int a, b;
printf ("\n Enter two number");
scanf ("\%d %d ", &a ,&b);
add (a, b);
}

Add (int x, int y)


{
int z;
z = x +y;
printf(“The addition of two no is %d ”,z);
return (0);
}

3. Function with no arguments and return values


In this category a function does not receive any value from calling function but it returns values to the
calling function.
Example:

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);
}

4. Function with arguments and return values


In this category a function receives values from calling function and it also returns values to the calling
function.

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);
}

4.5 Function prototype


Functions declaration and prototypes
Any function by default returns an int value. If we desire that a function should return a value other than an int,
then it is necessary to explicitly mention so in the calling functions as well as in the called function. e.g

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.

/* program to find the first n entries in the fibonacci */


#include<stdio.h>
main(0
{
int i,n;
int fibonacci(int,i);
printf(“Enter no. of entries:”); /* read the number of entries */
scanf(“%d”,&n);
printf(“The fibonacci series: \n”); /* calculate and display the fibonacci series */
for(i=1; i<n; i+=)
printf(“%d\n”,fibonacci(i) );
} /* end of main() */

int fibonacci(int x) /* function to find the nth fibonacci no */


{
if (( x== 1) || (x = = 2))
return(1);
else
return(fibonacci(x-1) + fibonacci(x-2));

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 -

Enter two numbers whose GCD is to be found: 47 10


GCD of 47 and 10 is = 1

Enter two numbers whose GCD is to be found: 16 64


GCD of 16 and 64 is = 16

4.8 Passing arguments


4.8.1 Call by value
In the preceding examples we have seen that whenever we called a function we have always passed the
values of variables to the called function. Such function calls are called 'calls by value' by this what it meant is that
on calling a function we are passing values of variables to it.

The example of call by value are shown below ;


sum = Fun_sum (a, b, c);

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);
}

The output of the above program would be;


x = 20 y = 10

Sumit Sar
Department of Computer Science & Engineering
BIT, Durg
- 11 -
a =10 b =20

4.8.2 Call by reference

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

4.9 Passing array to function

We can pass an array to the function by two methods:


1. Pass the value of individual array elements (call by value)
2. Pass an entire array to the function (call by reference)

Pass the value of individual array elements (call by value)


To understand the first method .let we take an example.
#include<conio.h>
#include<stdio.h>

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);
}

Passing an entire array to the function (call by reference)


One dimensional array
#include<conio.h>
#include<stdio.h>

main()
{
int a[5]={1,3,5,7,9},i;
clrscr ();
Funval (&a);
}

Funval (int *g)


{
int i;
for (i=0;i<5;i++)
{
Printf (“ %d ”, a[i]);
}

Two dimensional array


We can pass an entire 2-D array in three ways.

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);
}

Funval (int *g)


{
int i;
Printf (“ %d ”, *(g+2*3+2)); // *(base address + row no * total no of column + column no)
}
*---------------output---------------------*
17

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);
}

Funval (int (*g)[3])


{
int i;
Printf (“ %d ”, *(*(g+2)+2));
}
*---------------output---------------------*
17

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);
}

Funval (int g[3][3])


{
int i;
Printf (“ %d ”, g[2][2]);
}
*---------------output---------------------*
17

The following point must be noted about functions

1. C program is a collection of one or more functions


2. A function gets called when the function name is followed by a semicolon for e.g.
main ( )
{
message ( );
}

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 -
}

5. A function can be called any number of times for e.g.


main ()
{
message ( );
message ( );
}
message ( )
{
printf ("\n Hello");
}
6. The order in which the functions are defined in a program and the order in which they get called need not
necessarily be same for e.g.
main ( );
{
message1 ( );
message2 ( );
}
message2 ( )
{
printf ("\n I am learning C");
}
message1 ( )
{
printf ( "\n Hello ");
}

7. A function can call itself such a process as called 'recursion'.

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 -
}

9. Any C program contains at least one function.


10. If a program contains only one function, it must be main ( )
11. In a C program if there are more than one functional present then one of these functional must be main ( )
because program execution always begins with main ( )
12. There is no limit on the number of functions that might be present in a C program.
13. Each function in a program is called in the sequence specified by the function calls in main ( )
14. After each function has done its thing, control returns to the main ( ), when main ( ) runs out of function calls,
the program ends.

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.

Similarly structure date date_of_mar etc.

To get the actual month, say, of date of marriage,

We say date_of_marriage .date

To get the actual year of 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

today. month month


today. day
today day

today. year year


today.month =9;
today.day = 12;
today.year = 1981;
printf ("Today's date is %d/%d/%d\n", today.month,today.day,today.year );
}

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.

4.11 Array of structures


So far we have seen that how to declare and initialize the structure variable. Now if we want to access or to store
the subject marks of, say, 10 students. In that case we may declare an array of structure, each element of array
representing a structure variable.

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]

4.12 Array within structure


If we want to store the information about students that is the student name, student roll no and branch
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]

4.13 structure within structure


Let us take an example to understand the structure within structure.
Suppose we want to store the information of student i.e. name, roll no & subject marks then the format of structure
will be:

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)
}

4.14 structure and functions


We can pass the structure member by two method i.e. call by value and call by reference
 In call by value we pass the structure member individually in the function
For example
Struct info
{
int rollno;
char name[10];
};
main()
{
int ;
struct info student={22,”ravi”};
fun (student.rollno, student. name);
}

Fun (int rollno, char name [])


{
Printf(“%d %s”,rollno,name);
}

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);
}

Fun (struct info *student)


{
Printf (“%d %s”, student->rollno, student->name);
}

4.15 Introduction to Unions


Unions are also a derived data type. Union’s like structures contain members whose individual data types may differ
from one another. All the members in the union share the same storage area in the memory. Advantage of using
union is to conserve memory. They are useful for applications involving multiple members, where values need not
be assigned to all of the members at one time
Syntax:
Union tag name Tag name is optional
{
Data type member1;
Data type member2;
Data type member3;

}

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

*********Memory representation of structure and union*********

Struct info Stud.a Stud.c Stud.f


{
Int a;
Char c;
Float f;
800 801 802 803 804 805 806
} stud;

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

You might also like