0% found this document useful (0 votes)
48 views46 pages

Unit 5 User Defined Functions & Structures

The document provides an overview of user-defined functions in C programming, explaining their definition, advantages, types, and key elements such as declaration, calling, and definition. It discusses the differences between actual and formal parameters, as well as the methods of passing parameters to functions, including call by value and call by reference. Additionally, it outlines various categories of functions based on parameters and return values, and describes inter-function communication methods.

Uploaded by

jhadaditya95
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)
48 views46 pages

Unit 5 User Defined Functions & Structures

The document provides an overview of user-defined functions in C programming, explaining their definition, advantages, types, and key elements such as declaration, calling, and definition. It discusses the differences between actual and formal parameters, as well as the methods of passing parameters to functions, including call by value and call by reference. Additionally, it outlines various categories of functions based on parameters and return values, and describes inter-function communication methods.

Uploaded by

jhadaditya95
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/ 46

UNIT V USER DEFINED FUNCTIONS & STRUCTURES

FUNCTIONS:

User‐Defined Functions

Definition: A function is a block of code/group of statements/self contained block of statements/


basic building blocks in a program that performs a particular task. It is also known
as procedure or subroutine or module, in other programming languages.

To perform any task, we can create function. A function can be called many times. It
provides modularity and code reusability.
Advantage of functions

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code
again and again.

2) Code optimization

It makes the code optimized we don't need to write much code.

3) Easily to debug the program.

Example: Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or
not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of
code.

But if you use functions, you need to write the logic only once and you can reuse it several times.

Types of Functions

There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc. You just need to include appropriate
header files to use these functions. These are already declared and defined in C
libraries. oints to be Remembered

System defined functions are declared in header files

System defined functions are implemented in .dll files. (DLL stands for Dynamic Link
Library).

To use system defined functions the respective header file must be included.

2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces complexity of a big program and optimizes
the code. Depending upon the complexity and requirement of the program, you can create
as many user-defined functions as you want.
ELEMENTS OF USER-DEFINED FUNCTINS :

In order to write an efficient user defined function, the programmer must familiar with the
following three elements.

1 : Function Declaration. (Function Prototype).

2 : Function Call.

3 : Function Definition

Function Declaration. (Function Prototype).

A function declaration is the process of tells the compiler about a function name.

Syntax

return_type function_name(parameter/argument);

return_type function-name();

Ex : int add(int a,int b);

int add();
Note: At the time of function declaration function must be terminated with ;.

Calling a function/function call

When we call any function control goes to function body and execute entire code.

Syntax : function-name();

function-name(parameter/argument);

return value/ variable = function-name(parameter/argument);

Ex : add(); // function without parameter/argument

add(a,b); // function with parameter/argument

c=fun(a,b); // function with parameter/argument and return values

Defining a function.

Defining of function is nothing but give body of function that means write logic inside function
body.

Syntax

return_ type function-name(parameter list) // function header.

declaration of variables;

body of function; // Function body

return statement; (expression or value) //optional

Eg: int add( int x, int y) int add( int x, int y)

{ {

int z; ( or ) return ( x + y );

z = x + y; }
return z;

The execution of a C program begins from the main() function.

When the compiler encounters functionName(); inside the main function, control of the program
jumps to

void functionName()

And, the compiler starts executing the codes inside the user-defined function.

The control of the program jumps to statement next to functionName(); once all the codes inside
the function definition are executed.

Example:

#include<stdio.h>
#include<conio.h>

void sum(); // declaring a function

clrsct();

int a=10,b=20, c;

void sum() // defining function

c=a+b;

printf("Sum: %d", c);

void main()

sum(); // calling function

Output

Sum:30

Example:

#include <stdio.h>

int addNumbers(int a, int b); // function prototype

int main()

int n1,n2,sum;

printf("Enters two numbers: ");

scanf("%d %d",&n1,&n2);

sum = addNumbers(n1, n2); // function call


printf("sum = %d",sum);

return 0;

int addNumbers(int a,int b) // function definition

int result;

result = a+b;

return result; // return statement

Return Statement
Syntax of return statement

Syntax : return; // does not return any value

or

return(exp); // the specified exp value to calling function.

For example,

return a;

return (a+b);

The return statement terminates the execution of a function and returns a value to the calling
function. The program control is transferred to the calling function after return statement.

In the above example, the value of variable result is returned to the variable sum in
the main() function.

PARAMETERS :

parameters provides the data communication between the calling function and called function.

They are two types of parametes


1 : Actual parameters.

2 : Formal parameters.

1 : Actual Parameters : These are the parameters transferred from the calling function (main
program) to the called function (function).

2 : Formal Parameters :These are the parameters transferred into the calling function (main
program) from the called function(function).

 The parameters specified in calling function are said to be Actual Parameters.

 The parameters declared in called function are said to be Formal Parameters.

 The value of actual parameters is always copied into formal parameters.

Ex : main()

fun1( a , b ); //Calling function

fun1( x, y ) //called function

..... .

Where

a, b are the Actual Parameters

x, y are the Formal Parameters

Difference between Actual Parameters and Formal Parameters

Actual Parameters Formal Parameters

1 : Actual parameters are used in calling 1 : Formal parameters are used in the
function when a function is invoked. function header of a called function.
Ex : c=add(a,b); Ex : int add(int m,int n);

Here a,b are actual parameters. Here m,n are called formal parameters.

2 : Actual parameters can be constants, 2 : Formal parametes should be only


variables or expression. variable. Expression and constants are not
allowed.
Ex : c=add(a,b) //variable
Ex : int add(int m,n); //CORRECT
c=add(a+5,b); //expression.
int add(int m+n,int n) //WRONG
c=add(10,20); //constants.
int add(int m,10); //WRONG

3 : Actual parameters sends values to the 3 : Formal parametes receive values from
formal parameters. the actual parametes.

Ex : c=add(4,5); Ex : int add(int m,int n);

Here m will have the value 4 and n will


have the value 5.

4 : Address of actual parameters can be sent 4 : if formal parameters contains address,


to formal parameters they should be declared as pointers.

PASSING PARAMETERS TO FUNCTIONS :There are two ways to pass value or data to
function in C language: call by value and call by reference. Original value is not modified in
call by value but it is modified in call by reference.

The called function receives the information from the calling function through the parameters.
The variables used while invoking the calling function are called actual parameters and the
variables used in the function header of the called function are called formal parameters.

C provides two mechanisms to pass parameters to a function.

1 : Pass by value (OR) Call by value.

2 : Pass by reference (OR) Call by Reference.

1 : Pass by value (OR) Call by value :

In call by value, value being passed to the function is locally stored by the function parameter in
stack memory location. If you change the value of function parameter, it is changed for the
current function only. It will not change the value of variable inside the caller method such as
main().

Or
When a function is called with actual parameters, the values of actual parameters are copied into
formal parameters. If the values of the formal parametes changes in the function, the values of
the actual parameters are not changed. This way of passing parameters is called pass by value or
call by value.

Ex :

#include<stdio.h>

#include<conio.h>

void swap(int ,int );

void main()

int i,j;

printf("Enter i and j values:");

scanf("%d%d",&i,&j);

printf("Before swapping:%d%d\n",i,j);

swap(i,j);

printf("After swapping:%d%d\n",i,j);

getch();

void swap(int a,int b)

int temp;

temp=a;

a=b;

b=temp;

Output
Enter i and j values: 10 20

Before swapping: 10 20

After swapping: 10 20

2 : Pass by reference (OR) Call by Reference : In pass by reference, a function is called with
addresses of actual parameters. In the function header, the formal parameters receive the
addresses of actual parameters. Now the formal parameters do not contain values, instead they
contain addresses. Any variable if it contains an address, it is called a pointer variable. Using
pointer variables, the values of the actual parameters can be changed. This way of passing
parameters is called call by reference or pass by reference.

Ex : #include<stdio.h>

#include<conio.h>

void swap(int *,int *);

void main()

int i,j;

printf("Enter i and j values:");

scanf("%d%d",&i,&j);

printf("Before swapping:%d%d\n",i,j);

swap(&i ,&j);

printf("After swapping:%d%d\n",i,j);

void swap(int *a,int *b)

int temp;

temp=*a;

*a=*b;

*b=temp;
}

Output

Enter i and j values: 10 20

Before swapping:10 20

After swapping: 20 10

Differnce between Call by value and Call by reference

Call by value Call by Reference

1 : When a function is called the values of 1 : When a function is called the address of
variables are passed variables are passed.

2 : Change of formal parameters in the 2 : The actual parameters are changed since
function will not affect the actual the formal parameters indirectly manipulate
parameters in the calling function. the actual parametes.

3 : Execution is slower since all the values 3 : Execution is faster since only address
have to be copied into formal parameters. are copied.

1 : Functions with no Parameters and no Return Values.

2 : Functions with no Parameters and Return Values.

3 : Functions with Parameters and no Return Values.

4 : Functions with Parameters and Return Values.

1 : Functions with no Parameters and no Return Values :

1 : In this category, there is no data transfer between the calling function and called function.

2 : But there is flow of control from calling function to the called function.

3 : When no parameters are there , the function cannot receive any value from the calling
function.

4: When the function does not return a value, the calling function cannot receive any value from
the called function.

Ex #include<stdio.h>
#include<conio.h>

void sum();

void main()

sum();

getch();

void sum()

int a,b,c;

printf("enter the values of a and b");

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

c=a+b;

printf("sum=%d",c);

2 : Functions with no Parameters and Return Values.


1 : In this category, there is no data transfer between the calling function and called function.

2 : But there is data transfer from called function to the calling function.

3 : When no parameters are there , the function cannot receive any values from the calling
function.

4: When the function returns a value, the calling function receives one value from the called
function.

Ex : #include<stdio.h>

#include<conio.h>

int sum();
void main()

int c;

clrscr();

c=sum();

printf("sum=%d",c);

getch();

int sum()

int a,b,c;

printf("enter the values of a and b");

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

c=a+b;

return c;

3 : Functions with Parameters and no Return Values.

1 : In this category, there is data transfer from the calling function to the called function using
parameters.

2 : But there is no data transfer from called function to the calling function.

3 : When parameters are there , the function can receive any values from the calling function.

4: When the function does not return a value, the calling function cannot receive any value from
the called function.

Ex : #include<stdio.h>

#include<conio.h>
void sum(int a,int b);

void main()

int m,n;

clrscr();

printf("Enter m and n values:");

scanf("%d%d",&m,&n);

sum(m,n);

getch();

void sum(int a,int b)

int c;

c=a+b;

printf("sum=%d",c);

4 : Functions with Parameters and Return Values.

1 : In this category, there is data transfer from the calling function to the called function using
parameters.

2 : But there is no data transfer from called function to the calling function.

3 : When parameters are there , the function can receive any values from the calling function.

4: When the function returns a value, the calling function receive a value from the called
function.

Ex : #include<stdio.h>

#include<conio.h>

int sum(int a,int b);


void main()

int m,n,c;

clrscr();

printf("Enter m and n values");

scanf("%d%d",&m,&n);

c=sum(m,n);

printf("sum=%d",c);

getch();

int sum(int a,int b)

int c;

c=a+b;

return c;

Inter‐Function Communication
When a function gets executed in the program, the execution control is transferred from calling
function to called function and executes function definition, and finally comes back to the calling
function. In this process, both calling and called functions have to communicate each other to
exchange information. The process of exchanging information between calling and called
functions is called as inter function communication.

In C, the inter function communication is classified as follows...

 Downward Communication

 Upward Communication
 Bi-directional Communication

Downward Communication

In this type of inter function communication, the data is transferred from calling function to
called function but not from called function to calling function. The functions with parameters
and without return value are considered under downward communication. In the case of
downward communication, the execution control jumps from calling function to called function
along with parameters and executes the function definition,and finally comes back to the calling
function without any return value. For example consider the following program...

Example:

#include <stdio.h>

#include<conio.h>

void main(){

int num1, num2 ;

void addition(int, int) ; // function declaration

clrscr() ;

num1 = 10 ;

num2 = 20 ;

printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;

addition(num1, num2) ; // calling function

getch() ;
}

void addition(int a, int b) // called function

printf("SUM = %d", a+b) ;

Output

SUM=30

Upward Communication

In this type of inter function communication, the data is transferred from called function to
calling function but not from calling function to called function. The functions without
parameters and with return value are considered under upward communication. In the case of
upward communication, the execution control jumps from calling function to called function
without parameters and executes the function definition, and finally comes back to the calling
function along with a return value. For example consider the following program...

Exmaple:

#include <stdio.h>

#include<conio.h>

void main(){

int result ;

int addition() ; // function declaration

clrscr() ;

result = addition() ; // calling function

printf("SUM = %d", result) ;

getch() ;

int addition() // called function


{

int num1, num2 ;

num1 = 10;

num2 = 20;

return (num1+num2) ;

Output

SUM=30

Bi - Directional Communication

In this type of inter function communication, the data is transferred from calling function to
called function and also from called function to calling function. The functions with parameters
and with return value are considered under bi-directional communication. In the case of bi-
drectional communication, the execution control jumps from calling function to called function
along with parameters and executes the function definition, and finally comes back to the calling
function along with a return value. For example consider the following program...

Example:

#include <stdio.h>

#include<conio.h>

void main(){

int num1, num2, result ;

int addition(int, int) ; // function declaration

clrscr() ;

num1 = 10 ;

num2 = 20 ;

result = addition(num1, num2) ; // calling function

printf("SUM = %d", result) ;


getch() ;

int addition(int a, int b) // called function

return (a+b) ;

Output

SUM=30

Standard Functions
The standard functions are built-in functions. In C programming language, the standard functions
are declared in header files and defined in .dll files. In simple words, the standard functions can
be defined as "the ready made functions defined by the system to make coding more easy". The
standard functions are also called as library functions or pre-defined functions.

In C when we use standard functions, we must include the respective header file
using #include statement. For example, the function printf() is defined in header
file stdio.h (Standard Input Output header file). When we use printf() in our program, we must
include stdio.h header file using #include<stdio.h> statement.

C Programming Language provides the following header files with standard functions.

Header
Purpose Example Functions
File

stdio.h Provides functions to perform standard I/O operations printf(), scanf()

conio.h Provides functions to perform console I/O operations clrscr(), getch()

math.h Provides functions to perform mathematical operations sqrt(), pow()

string.h Provides functions to handle string data values strlen(), strcpy()

stdlib.h Provides functions to perform general functions calloc(), malloc()


Provides functions to perform operations on time and
time.h time(), localtime()
date

Provides functions to perform - testing and mapping of


ctype.h isalpha(), islower()
character data values

setjump(),
setjmp.h Provides functions that are used in function calls
longjump()

Provides functions to handle signals during program


signal.h signal(), raise()
execution

Provides Macro that is used to verify assumptions made


assert.h assert()
by the program

Defines the location specific settings such as date


locale.h setlocale()
formats and currency symbols

Used to get the arguments in a function if the arguments va_start(), va_end(),


stdarg.h
are not specified by the function va_arg()

errno.h Provides macros to handle the system calls Error, errno

float.h Provides constants related to floating point data values

Defines the maximum and minimum values of various


limits.h
variable types like char, int and long

stddef.h Defines various variable types

graphics.h Provides functions to draw graphics. circle(), rectangle()

STANDARD „C‟ LIBRARY FUNCTIONS

1 : stdio.h

2 : stdlib.h
3 : string.h

4 : math.h

5 : ctype.h

6 : time.h

1 : STANDARD I/O LIBRARY FUNCTIONS <STDIO.H>

Functions DataType Purpose

printf() int Send data items to the standared output device.

scanf() int Enter data items from the standard input device.

gets(s) char Enter string s from the standard input device.

getc(f) int Enter a string character from file f.

getchar() int Enter a single character from the standard input device.

putc(c,f) int Send a single character to file f.

puts(s) int Send string s to the standard output device.

putchar(c) int Send a single character to the standard output device.

fgetc(f) int Enter a single character from file f.

fgets(s,I,f) char Enter string s, containing I characters, from file f.

fprintf(f) int Send data items to file f.

fscanf(f) int Enter data items from file f.

fputc(c,f) int Send a single character to file f.

fputs(s,f) int Send string s to file f.

fread(s,il,i2,f) int Enter i2 data items, each of size i1 bytes, from file f.

fclose(f) int Close file f, return 0 if file is successfully closed.

2 : STANDARD LIBRARY FUNCTIONS <STDLIB.H>


Functions DataType Purpose

abs(i) int Return the absolute value of i.

atof(s) double Convert string s to a double-precesion quantity.

calloc(u1,u2) void* Allocate memory for an array having u1 elements, each of


length u2 bytes. Return a pointer to the beginning of the
allocated space.

exit(u) void Close all files and buffers, and terminate the program.

free(p) void Free a block of allocated memory whose beginning is


indicated by p.

malloc(u) void* Allocate u bytes of memory.

rand() int Return a random positive integer.

realloc(p,u) void* Allocate u bytes of new memory to the pointer variable p,


return a pointer to the beginning of the new memory space.

system(s) int Pass command string s to the operating system.

srand(u) void Initialize the random number generator.

3 : STRING LIBRARY FUNCTIONS <STRING.H>

Functions DataType Purpose

strlen() Finds length of string

strlwr() Converts a string to lowercase

strupr() Converts a string to uppercase

strcat() Appends one string at the end of another

strcpy() Copies a string into another

strcmp() Compares two strings

strrev() Reverses string


4 : MATH LIBRARY FUNCTIONS <MATH.H>

Functions DataType Purpose

acos(d) double Return the arc cosine of d.

atan(d) double Return the arc tangent of d.

asin(d) double Return the arc sine of d.

ceil(d) double Return a value rounded up to the next higher integer.

cos(d) double Return the cosine of d.

cosh(d) double Return the hyperbolic cosine of d.

exp(d) double Raise e to the power d.

fabs(d) double Return the absolute value of d.

floor(d) double Return a value rounded down to the next lower integer.

labs(l) long int Return the absolute value of l.

log(d) double Return the natural logarithm of d.

pow(d1,d2) double Return d1 raised to the d2 power.

sin(d) double Return the sine of d.

sqrt(d) double Return squre root of d.

tan(d) double Return the tangent of d.

5 : CHARACTER LIBRARY FUNCTIONS <CTYPE.H>

Functions DataType Purpose


isalnum(c) Int Determine if argument is alphanumeric. Return nonzero value
if true, 0 otherwise.

isalpha(c) Int Determine if argument is alphabetic. Return nonzero value if


true, 0 otherwise.

isascii(c) Int Determine if argument is an ASCII character,. Return nonzero


value if true, 0 otherwise.

isdigit(c) Int Determine if argument is a decimal digit. Return nonzero


value if true, 0 otherwise.

isgraph(c) Int Determine if argument is a graphic printing ASCII Character.


Return nonzero value if true, 0 otherwise.

islower(c) Int Determine if argument is lowercase. Return nonzero value if


true, 0 otherwise.

isprint(c) Int Determine if argument is a printing ASCII character. Return


nonzero value if true, 0 otherwise.

isspace(c) Int Determine if argument is a whitespace character. Return


nonzero value if true, 0 otherwise.

isupper(c) Int Determine if argument is uppercase. Return nonzero value if


true, 0 otherwise.

toascii(c) Int Convert value of argument to ASCII

tolower(c) Int Convert letter to lowercase

toupper(c) Int Convert letter to uppercase.

6 : TIME LIBRARY FUNCTIONS <TIME.H>

Functions DataType Purpose

difftime(11,12) double Return the time difference 11-12, where 11 and 12


represent elapsed time beyond a designated base time.

time(p) long int Return the number of seconds elapsed beyond a designated
base time.
Structure Definition
Structure is a user defined data type which hold or store heterogeneous/different types data item
or element in a single variable. It is a Combination of primitive and derived data type.

or
A structure is a collection of one or more data items of different data types, grouped together
under a single name.

Variables inside the structure are called members of structure.

Each element of a structure is called a member.

struct keyword is used to define/create a structure. struct define a new data type which is a
collection of different type of data.

Syntax

struct structure_name /tag name

data_type member1;

data_type member2;

data_type member n;

};

Note: Don't forget the semicolon }; in the ending line.

Example

struct employee

{ int id;

char name[50];

float salary;

};
Here, struct is the keyword, employee is the tag name of
structure; id, name and salary are the members or fields of the structure. Let's
understand it by the diagram given below:

Syntax to create structure variable

struct tagname/structure_name variable;

Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily.
There are two ways to declare structure variable:

1. By struct keyword within main() function/ Declaring Structure variables separately

2. By declaring variable at the time of defining structure/ Declaring Structure Variables


with Structure definition

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared
within the main function.

struct employee

{ int id;
char name[50];

float salary;

};

Now write given code inside the main() function.

struct employee e1, e2;

2nd way:

Let's see another way to declare variable at the time of defining structure.

struct employee

{ int id;

char name[50];

float salary;

}e1,e2;

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the
structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main()
function.

Structure Initialization
structure variable can also be initialized at compile time.

struct Patient

float height;

int weight;
int age;

};

struct Patient p1 = { 180.75 , 73, 23 }; //initialization

or

struct patient p1;

p1.height = 180.75; //initialization of each member separately

p1.weight = 73;

p1.age = 23;

Accessing Structures/ Accessing members of structure


There are two ways to access structure members:

1. By . (member or dot operator)

2. By -> (structure pointer operator)

When the variable is normal type then go for struct to member operator.

When the variable is pointer type then go for pointer to member operator.

Any member of a structure can be accessed as:

structure_variable_name.member_name

Example

struct book

char name[20];

char author[20];

int pages;

};
struct book b1;

for accessing the structure members from the above example

b1.name, b1.author, b1.pages:

Example

struct emp

int id;

char name[36];

int sal;

};

sizeof(struct emp) // --> 40 byte (2byte+36byte+2byte)

Example of Structure in C

#include<stdio.h>

#include<conio.h>

struct emp

int id;

char name[36];

float sal;

};

void main()

struct emp e;

clrscr();

printf("Enter employee Id, Name, Salary: ");


scanf("%d",&e.id);

scanf("%s",&e.name);

scanf("%f",&e.sal);

printf("Id: %d",e.id);

printf("\nName: %s",e.name);

printf("\nSalary: %f",e.sal);

getch();

Output

Output: Enter employee Id, Name, Salary: 5 Spidy 45000

Id : 05

Name: Spidy

Salary: 45000.00

Example

#include <stdio.h>

#include <string.h>

struct employee

{ int id;

char name[50];

}e1; //declaring e1 variable for structure

int main( )

//store first employee information


e1.id=101;

strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array

//printing first employee information

printf( "employee 1 id : %d\n", e1.id);

printf( "employee 1 name : %s\n", e1.name);

return 0;

Output:

employee 1 id : 101

employee 1 name : Sonoo Jaiswal

Difference Between Array and Structure

Structure is the collection of


1 Array is collection of homogeneous data.
heterogeneous data.
Structure elements are access using .
2 Array data are access using index.
operator.
3 Array allocates static memory. Structures allocate dynamic memory.
Array element access takes less time than Structure elements takes more time than
4
structures. Array.

Nested Structures
structure can have another structure as a member. There are two ways to define nested structure
in c language:

1. By separate structure

2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a
member. Let's see the code of nested structure.
struct Date

int dd;

int mm;

int yyyy;

};

struct Employee

int id;

char name[20];

struct Date doj;

}emp1;

2) Embedded structure

struct Employee

int id;

char name[20];

struct Date

int dd;

int mm;

int yyyy;

}doj;

}emp1;
Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as


given below:

e1.doj.dd

e1.doj.mm

e1.doj.yyyy

Arrays of Structures
Array of structures to store much information of different data types. Each element of the array
representing a structure variable. The array of structures is also known as collection of
structures.

Ex : if you want to handle more records within one structure, we need not specify the number of
structure variable. Simply we can use array of structure variable to store them in one structure
variable.

Example : struct employee emp[5];

Example of structure with array that stores information of 5 students and prints it.

#include<stdio.h>

#include<conio.h>

#include<string.h>

struct student{

int rollno;

char name[10];

};

void main(){

int i;

struct student st[5];

clrscr();
printf("Enter Records of 5 students");

for(i=0;i<5;i++){

printf("\nEnter Rollno:");

scanf("%d",&st[i].rollno);

printf("\nEnter Name:");

scanf("%s",&st[i].name);

printf("\nStudent Information List:");

for(i=0;i<5;i++){

printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);

getch();

Output:

Enter Records of 5 students

Enter Rollno:1

Enter Name:Sonoo

Enter Rollno:2

Enter Name:Ratan

Enter Rollno:3

Enter Name:Vimal

Enter Rollno:4

Enter Name:James

Enter Rollno:5

Enter Name:Sarfraz
Student Information List:

Rollno:1, Name:Sonoo

Rollno:2, Name:Ratan

Rollno:3, Name:Vimal

Rollno:4, Name:James

Rollno:5, Name:Sarfraz

Structures and Functions


A structure can be passed as a function argument just like any other variable. This raises a few
practical issues.

PASSING STRUCTURE TO FUNCTION IN C:

It can be done in below 3 ways.

1. Passing structure to a function by value

2. Passing structure to a function by address(reference)

3. No need to pass a structure – Declare structure variable as global

The general format of sending a copy of a structure to the called function is:

Function_name(structure_variable_name);

The called function takes the following form:

data_type function_name(struct tag_name var)

{
----------

----------

return(exp);

PASSING STRUCTURE TO FUNCTION IN C BY VALUE:

#include <stdio.h>

#include <string.h>

struct student

int id;

char name[20];

float percentage;

};

void func(struct student record);

int main()

struct student record;

record.id=1;

strcpy(record.name, "Raju");

record.percentage = 86.5;

func(record);

return 0;

void func(struct student record)


{

printf(" Id is: %d \n", record.id);

printf(" Name is: %s \n", record.name);

printf(" Percentage is: %f \n", record.percentage);

Output

Id is: 1

Name is: Raju

Percentage is: 86.500000

PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS:

#include <stdio.h>

#include <string.h>

struct student

int id;

char name[20];

float percentage;

};

void func(struct student *record);

int main()

struct student record;

record.id=1;

strcpy(record.name, "Raju");

record.percentage = 86.5;
func(&record);

return 0;

void func(struct student *record)

printf(" Id is: %d \n", record->id);

printf(" Name is: %s \n", record->name);

printf(" Percentage is: %f \n", record->percentage);

EXAMPLE PROGRAM TO DECLARE A STRUCTURE VARIABLE AS GLOBAL IN


C:

#include <stdio.h>

#include <string.h>

struct student

int id;

char name[20];

float percentage;

};

struct student record; // Global declaration of structure

void structure_demo();

int main()

record.id=1;
strcpy(record.name, "Raju");

record.percentage = 86.5;

structure_demo();

return 0;

void structure_demo()

printf(" Id is: %d \n", record.id);

printf(" Name is: %s \n", record.name);

printf(" Percentage is: %f \n", record.percentage);

Passing a copy of entire structure to a function

struct std

int no;

float avg;

};

struct std a;

void fun(struct std p);

void main()
{

clrscr();

a.no=12;

a.avg=13.76;

fun(a);

getch();

void fun(struct std p)

printf("number is%d\n",p.no);

printf("average is%f\n",p.avg);

Passing Structures through Pointers


Example

#include <stdio.h>

#include <string.h>

struct student

int id;

char name[30];

float percentage;
};

int main()

int i;

struct student record1 = {1, "Raju", 90.5};

struct student *ptr;

ptr = &record1;

printf("Records of STUDENT1: \n");

printf(" Id is: %d \n", ptr->id);

printf(" Name is: %s \n", ptr->name);

printf(" Percentage is: %f \n\n", ptr->percentage);

return 0;

OUTPUT:

Records of STUDENT1:
Id is: 1
Name is: Raju

Percentage is: 90.500000

Self‐referential Structures
A structure consists of at least a pointer member pointing to the same structure is known as a
self-referential structure. A self referential structure is used to create data structures like linked
lists, stacks, etc. Following is an example of this kind of structure:
A self-referential structure is one of the data structures which refer to the pointer to (points) to
another structure of the same type. For example, a linked list is supposed to be a self-referential
data structure. The next node of a node is being pointed, which is of the same struct type. For
example,

Syntax : struct tag_name

type member1;

type membere2;

: :

: :

typeN memberN;

struct tag_name *name;

Where *name refers to the name of a pointer variable.

Ex:

struct emp

int code;

struct emp *name;

You might also like