KEMBAR78
Notes of Array Functions Structure Union String | PDF | Parameter (Computer Programming) | Computer Program
0% found this document useful (0 votes)
5 views23 pages

Notes of Array Functions Structure Union String

The document provides a comprehensive overview of arrays in programming, detailing their structure, types (single and multi-dimensional), properties, and advantages. It includes examples of array declaration, initialization, accessing elements, and operations such as summation and string manipulation. Additionally, it explains the use of library functions in C for handling strings and arrays, emphasizing the importance of user-defined functions.

Uploaded by

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

Notes of Array Functions Structure Union String

The document provides a comprehensive overview of arrays in programming, detailing their structure, types (single and multi-dimensional), properties, and advantages. It includes examples of array declaration, initialization, accessing elements, and operations such as summation and string manipulation. Additionally, it explains the use of library functions in C for handling strings and arrays, emphasizing the importance of user-defined functions.

Uploaded by

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

ARRAY

Array is the collection of similar data types or collection of similar entity stored in contiguous memory
location. Array of character is a string. Each data item of an array is called an element. And each
element is unique and located in separated memory location. Each of elements of an array share a
variable but each element having different index no. known as subscript.

An array can be a single dimensional or multi-dimensional and number of subscripts determines its
dimension. And number of subscript is always starts with zero. One dimensional array is known as
vector and two dimensional arrays are known as matrix.

Properties of an array
1. The type of an array is the data type of its elements.
2. The location of an array is the location of its first element.
3. The length of an array is the number of data elements in an array.
4. The size of the array is the length of the array times the size of the elements, but the size of the array
is usually referred as the product of subscript used.
________________________________________________________________________

ADVANTAGES: Array variable can store more than one value at a time where other variable can store
one value at a time.

Example:
int arr[100];
int mark[100];

DECLARATION OF AN ARRAY :
Its syntax is :
Data type array name [size];

int arr[100];
int mark[100];
int a[5]={10,20,30,100,5}
The declaration of an array tells the compiler that, the data type, name of the array, size of the array and
for each element it occupies memory space. Like for int data type, it occupies 2 bytes for each element
and for float it occupies 4 byte for each element etc.

We can represent individual array as :


int ar[5];
ar[0], ar[1], ar[2], ar[3], ar[4];
Symbolic constant can also be used to specify the size of the array as:
#define SIZE 10;

INITIALIZATION OF AN ARRAY:
After declaration element of local array has garbage value. If it is global or static array then it will be
automatically initialize with zero. An explicitly it can be initialize that Data type array name [size] =
{value1, value2, value3…}

Example:
in ar[5]={20,60,90, 100,120}
Array subscript always start from zero which is known as lower bound and upper value is known as
upper bound and the last subscript value is one less than the size of array.
The array elements are standing in continuous memory locations and the amount of storage required for
hold the element depend in its size & type.

Total size in byte for 1D array is:


Total bytes=size of (data type) * size of array.
Example : if an array declared is:
int [20];
Total byte= 2 * 20 =40 byte.

ACCESSING OF ARRAY ELEMENT:

Once the array is declared, how individual elements in the array are accessed. This is done with the help
of subscripts (i.e., number specified in the square brackets following the array name).The subscript
specifies the elements position in the array. The array elements are numbered, starting from zero. The
first item stored at the address pointed by the array name itself. This can also be referred as position
0.Thus the first element of the array age is referred as age[0].The fourth element of the array is reoffered
as age[3].

/*Write a program to input values into an array and display them*/


#include<stdio.h>
int main()
{
int arr[5],i;
for(i=0;i<5;i++)
{
printf(“enter a value for arr[%d] \n”,i);
scanf(“%d”,&arr[i]);
}
printf(“the array elements are: \n”);
for (i=0;i<5;i++)
{
printf(“%d\t”,arr[i]);
}
return 0;
}

OUTPUT:
Enter a value for arr[0] = 12
Enter a value for arr[1] =45
Enter a value for arr[2] =59
Enter a value for arr[3] =98
Enter a value for arr[4] =21
The array elements are 12 45 59 98 21

Example: From the above example value stored in an array are and occupy its
memory addresses 2000, 2002, 2004, 2006, 2008 respectively.
a[0]=12, a[1]=45, a[2]=59, a[3]=98, a[4]=21
ar[0] ar[1] ar[2] ar[3] ar[4]

12 45 59 98 21
2000 2002 2004 2006 2008

Example 2:
/* Write a program to add 10 array elements */
#include<stdio.h>
void main()
{
int i ;
int arr [10];
int sum=0;
for (i=0; i<=9; i++)
{
printf (“enter the %d element \n”, i+1);
scanf (“%d”, &arr[i]);
}
for (i=0; i<=9; i++)
{
sum = sum + a[i];
}
printf (“the sum of 10 array elements is %d”, sum);
}

OUTPUT:

Enter a value for arr[0] =5


Enter a value for arr[1] =10
Enter a value for arr[2] =15
Enter a value for arr[3] =20
Enter a value for arr[4] =25
Enter a value for arr[5] =30
Enter a value for arr[6] =35
Enter a value for arr[7] =40
Enter a value for arr[8] =45
Enter a value for arr[9] =50
Sum = 275
while initializing a single dimensional array, it is optional to specify the size of array. If the size is
omitted during initialization then the compiler assumes the size of array equal to the number of
initializers.

For example:-

int marks[]={99,78,50,45,67,89};
If during the initialization of the number the initializers is less then size of array, then all the remaining
elements of array are assigned value zero .
For example:-
int marks[5]={99,78};
Here the size of the array is 5 while there are only two initializers so After this initialization, the value of
the rest elements are automatically occupied by zeros such as
Marks[0]=99 , Marks[1]=78 , Marks[2]=0, Marks[3]=0, Marks[4]=0
Again if we initialize an array like
int array[100]={0};
Then the all the element of the array will be initialized to zero. If the number of initializers is more than
the size given in brackets then the compiler will show an error.

For example:-

int arr[5]={1,2,3,4,5,6,7,8};//error
we cannot copy all the elements of an array to another array by simply assigning it to the other array
like, by initializing or declaring as
int a[5] ={1,2,3,4,5};
int b[5];
b=a;//not valid
(note:-here we will have to copy all the elements of array one by one, using for loop.)

Two dimensional arrays

Two dimensional array is known as matrix. The array declaration in both the array
i.e.in single dimensional array single subscript is used and in two dimensional array two subscripts are is
used.

Its syntax is

Data-type array name[row][column];

Or we can say 2-d array is a collection of 1-D array placed one below the other.

Total no. of elements in 2-D array is calculated as row*column

Example:-

int a[2][3];
Total no of elements=row*column is 2*3 =6

It means the matrix consist of 2 rows and 3 columns

For example:-

20 2 7
8 3 15

Positions of 2-D array elements in an array are as below


00 01 02
10 11 12

Accessing 2-d array /processing 2-d arrays

For processing 2-d array, we use two nested for loops. The outer for loop
corresponds to the row and the inner for loop corresponds to the column.

For example
int a[4][5];

for reading value:-


for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
scanf(“%d”,&a[i][j]);
}
}

For displaying value:-


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

Initialization of 2-d array:

2-D array can be initialized in a way similar to that of 1-D array.

for example:-

int mat[4][3]={11,12,13,14,15,16,17,18,19,20,21,22};
These values are assigned to the elements row wise, so the values of
elements after this initialization are

Mat[0][0]=11, Mat[1][0]=14, Mat[2][0]=17 Mat[3][0]=20


Mat[0][1]=12, Mat[1][1]=15, Mat[2][1]=18 Mat[3][1]=21
Mat[0][2]=13, Mat[1][2]=16, Mat[2][2]=19 Mat[3][2]=22

While initializing we can group the elements row wise using inner braces.
for example:-

int mat[4][3]={{11,12,13},{14,15,16},{17,18,19},{20,21,22}};
And while initializing , it is necessary to mention the 2nd dimension where 1st
dimension is optional.
int mat[][3];
int mat[2][3];
int mat[][];
int mat[2][]; invalid

If we initialize an array as

int mat[4][3]={{11},{12,13},{14,15,16},{17}};
Then the compiler will assume its all rest value as 0,which are not defined.
Mat[0][0]=11, Mat[1][0]=12, Mat[2][0]=14, Mat[3][0]=17
Mat[0][1]=0, Mat[1][1]=13, Mat[2][1]=15 Mat[3][1]=0
Mat[0][2]=0, Mat[1][2]=0, Mat[2][2]=16, Mat[3][2]=0

In memory map whether it is 1-D or 2-D, elements are stored in one


contiguous manner.

String
Array of character is called a string. It is always terminated by the NULL character. String is a one
dimensional array of character.

We can initialize the string as


char name[]={‘j’,’o’,’h’,’n’,’\o’};

Here each character occupies 1 byte of memory and last character is always NULL character. Where ’\o’
and 0 (zero) are not same, where ASCII value of ‘\o’ is 0 and ASCII value of 0 is 48. Array elements of
character array are also stored in contiguous memory allocation.

From the above we can represent as;


j o h n \o

The terminating NULL is important because it is only the way that the function that work with string can
know, where string end.

String can also be initialized as;


char name[]=”John”;

Here the NULL character is not necessary and the compiler will assume it automatically.

String constant (string literal)

A string constant is a set of character that enclosed within the double quotes and is also called a literal.
Whenever a string constant is written anywhere in a program it is stored somewhere in a memory as an
array of characters terminated by a NULL character (‘\o’).

Example – “m”
“Tajmahal”
“My age is %d and height is %f\n”
The string constant itself becomes a pointer to the first character in array.

Example-char crr[20]=”Taj mahal”;

1000 1001 1002 1003 1004 1005 1006 1007 1007 1008
T a j m a h a l \o

It is called base address.

String library function

There are several string library functions used to manipulate string and the prototypes for these functions
are in header file “string.h”.
Several string functions are

strcpy( ) Copies a string to an array


strncpy( ) Copies a portion of a string to an array
strcat( ) Appends one string to another
strcmp( ) Compares two strings
strncmp( ) Compares two strings upto a specified number of characters

strlen() This function return the length of the string. i.e. the number of characters in the string excluding
the terminating NULL character.

It accepts a single argument which is pointer to the first character of the string.

1000 1001 1002 1003 1004 1005 1006 1007 100 1009
T a j M A H a l \o

For examplestrlen(“ suresh”);


It return the value 6.

Example:-
#include<stdio.h>
#include<string.h>
void main()
{
char str[50];
print(”Enter a string:”);
gets(str);
printf(“Length of the string is %d\n”,strlen(str));
}

Output:

Enter a string: C in Depth


Length of the string is 8

strcmp()
This function is used to compare two strings. If the two string match, strcmp() return a value 0 otherwise
it return a non-zero value. It compare the strings character by character and the comparison stops when
the end of the string is reached or the corresponding characters in the two string are not same.
strcmp(s1,s2) return a value:
<0 when s1<s2
=0 when s1=s2
>0 when s1>s2
The exact value returned in case of dissimilar strings is not defined. We only know that if s1<s2 then a
negative value will be returned and if s1>s2 then a positive value will be returned.

/*String comparison…………………….*/
#include<stdio.h>
#include<string.h>
void main()
{
char str1[10],str2[10];
printf(“Enter two strings:”);
gets(str1);
gets(str2);
if(strcmp(str1,str2)==0)
{
printf(“String are same\n”);
}
else
{
printf(“String are not same\n”);
}
}
strcpy()
This function is used to copying one string to another string. The function strcpy(str1,str2) copies str2 to
str1 including the NULL character. Here str2 is the source string and str1 is the destination string.
The old content of the destination string str1 are lost. The function returns a pointer to destination
string str1.
Example:-
#include<stdio.h>
#include<string.h>
void main()
{
char str1[10],str2[10];
printf(“Enter a string:”);
scanf(“%s”,str2);
strcpy(str1,str2);
printf(“First string:%s\t\tSecond string:%s\n”,str1,str2);
strcpy(str,”Delhi”);
strcpy(str2,”Bangalore”);
printf(“First string :%s\t\tSecond string:%s”,str1,str2);
strcat()
This function is used to append a copy of a string at the end of the other string. If the first string is
“”Purva” and second string is “Belmont” then after using this function the string becomes
“PusvaBelmont”. The NULL character from str1 is moved and str2 is added at the end of str1. The 2nd
string str2 remains unaffected.
A pointer to the first string str1 is returned by the function.

INTRODUCTION to library function

A function, which is predefined in ‘C’ is known as library function, e.g., printf, scanf, getch, etc.,
are library functions. Appropriate header files must be included in the programme for using the library
functions.

In C functions can be classified into two categories


1. Library functions
2. User-defined functions

main() is the example of user-defined functions. printf() and scanf() are called the library functions. We
already user other library functions such as sqrt(),cos(),sin(),tan(),strcmp(),strcat() etc.This is greatest
features in C is that there is no conceptual difference between the user-defined functions and library
functions. For example, we can write a series of function to process matrices (such as square of given
number, finding cos value, finding sine value, etc).These are user-defined functions they are written by
user. After user, they can be compiled into libraries and distributed. To the users of the library, these
functions will act as library functions. That is these functions are predefined and precompiled; the users
need not worry about the functions work internally.
____________________________________________________________________________
1.3 NEED FOR USER-DEFINED FUNCTIONS
As discussed earlier, main () is a specially recognized pre-defined function in C.In every
program we have to use main () function to indicate where the program has been executed. While in any
program, does not utilizing the main function, it has face to the number of problems. In C, to write a
program to become too large and complex and the result has been debugging, testing, and maintaining
becomes difficult. In this situation, if a program it‟s large, program is divided into functional parts, then
each part may be independently coded and executed each part of program later combined into single
unit. These subprograms called function, this way to manipulate, the easier to understand, debug and
test.

In C, some time we need certain types of operation or calculations is repeated again and again in
the program. In this situation, we use user-defined functions. This saves both the time and space.

Main()

Fn1 Fn2 Fn3

Fn 2.1 Fn 2.2
___________________________________________________________________________

DEFINITION OF FUNCTIONS
A function is defined as a self-contained program which is written for the purpose of
accomplishing some task.

SYNTAX
returntype functionname(argument list)
{
declaration(s);
statement(s);
return(expression);
}
where
returntype->specifies the data type value to be returned by the function.
The return type is assumed to be of type int by default if it is not specified.
function name-> used to identify the function.

The rules for naming a function are Same as identifiers.

argument list->specified inside the parenthesis after the function name is optional.
Most functions have list of parameters and a return value that provides means for communication
between functions. The arguments in the function reference, which defines the data items that are
actually transferred, are referred as actual arguments or actual parameters.

All variables declared in function definitions are local variables. Their scope is visible known only in the
function in which they are defined. Functions arguments are als0 local variables.

A MULTI-FUNCTION PROGRAM

A function is a self-contained block of code that performs a particular task. Once a function has been
designed and packed, it can be treated as a „block box‟ that takes some data from the main program. All
that the program knows about a function is what goes in and what comes out. Every C program can be
designed using a collection of block boxes known as functions.

Consider the set of statement given below,

1#include<stdio.h>
2void func(); declaration
3void main()
4{
5printf(“Inside the Main Function”);
6func(); calling
7printf(“\n Again Inside Main Function”);
8}
9void func() //fn defi
10{
11printf(“\n Inside func Function”);
12}
The above set of statements defined a function called func(), which calls the function main(),its
exceeded and print the message is again inside main function.
This program will print the following output
Inside main function
Inside func function
Again inside main function

The above program contains two user-defined functions


(i) Main function
(ii) func () function

The program execution always begins with the main function. During execution of the main, the first
statements are printed “inside the main function”. Hence the function is called func().After it calls the
user-defined function to print the message inside func function. After again control passes to the main()
function, to print the message is called again the inside the main function.
Any function calls any other function. A „called function‟ also an another function. A function can be
called more than once. This is the main features of using function.

Except the starting point, there are no other predefined relationship, rules of precedence, or hierarchies
among the function that make up a complete program. The functions can be placed in any order. A
called function can be placed in any order. A called function can be placed either before or after the
calling function

Modular Programming

Modular programming is a software design technique breaking a large program down into a
number of functions, each of which performs a specific, well-defined task. This separates task is called
modules. These modules are carefully integrated to become a software system that satisfies the system
requirements. It is basically a “divide-and-conquer” approach to program solving.
Modules are typically incorporated into the program through interfaces. A module interface expresses
the elements that are provided and required by the module. The elements defined in the interface are
detectable by other modules. The implementation contains the working code that corresponds to the
elements declared in the interface.
____________________________________________________________________________

The use of functions in C has many advantages:

1. It facilitates top-down modular programming.


2. The length of a source program can be reduced by using functions at a appropriate Places.
3. It is easy to locate and isolate a faulty function for further investigations.
4. A function may be used by many other programs.

They are three elements that are related to user defined functions are:

1. Function definition
2. Function call
3. Function declaration

The function definition is an independent program module that is specially written to implement the
requirements of the function. In order to use this function we need to invoke it at a required place in the
program. This is known as the function call. The program (or a function) that calls the function is
referred to as the calling program or calling function. The calling program should declare any function
(like declaration of a variable).This is known as function declaration or function prototype.

Function Definition
A function definition, also known as function implementation it‟s include the following elements.

1. Function name
2. Function type
3. List of parameters
4. Local variable declaration
5. Function statements
6. A return statement

All the six elements are grouped into two parts, namely,
 Function header
 Function body

SYNTAX
return-type function-name(parameters)
{
Declarations;
Statements;
return value;
}
where,
return-type ->type of value returned by function or void if none

function-name-> unique name identifying function

parameters comma->separated list of types and names of parameters

value-> value returned upon termination (not needed if return-type void)

The list of parameters is a declaration on the form


type1 par1, ..., typen par n

And represents external values needed by the function. The list of parameters can be empty.
All declarations and statements that are valid in the main program can be used in the
Function definition, where they make up the function body.

Function Header
The function header consists of three parts: The function type (also known as return type, the function
name and the formal parameters list. Note that a semicolon is not used at the end of the function header.

Function Body

The function body contains the declarations and statements necessary for performing the required task.
The body enclosed in braces, contains three parts, and is given below:

1. Local declarations that specify the variables needed by the function


2. Function statements that perform the task of the function
3. A return statement that returns the value evaluated by the function

Example, computing averages

double average(double x, double y)


{
return (x+y)/2;
}
The return statement forces the function to return immediately, possibly before reaching the end of the
function body.

Function Call
A function can be called by simply using the function name followed by a list of actual parameters (or
arguments), if any, enclosed in parentheses.
SYNTAX

Variable=function-name (arguments);
Variable is assigned the return-value of the function.
The arguments are values with types corresponding to the function parameters.

Function Declaration

Like variables all function in a C program must be declared, before they are invoked. A function
declaration (also known as function prototype) consists of four parts.
1. Function type (return type)
2. Function name
3. Parameter list
4. Terminating semicolon

SYNTAX
return-type function-name(parameter types);
The function body is replaced by a semi-colon.
Parameters need not be named, it is sufficient to specify their types.

Example declaring average


double average(double, double);
Declaration is not necessary if the function definition precedes the first call.

EXAMPLE

Write a program for sum of two numbers and return the sum to the main function.
#include<stdio.h>
void main()
{
int addnum(int,int);
int sum,a,b;
printf(“\n Enter two number to be summed:”);
scanf(“%d %d”,&a,&b);
sum=addnum(a,b);
printf(“\n The sum of %d and %d is %d”,a,b,sum);
}
int addnum(num1,num2)
{
int tot;
tot=num1+num2;
return(tot);
}
Sample program output:
Enter two numbers to be summed: 15, 17
The of 15 and 17 is 32
The above program consists of two functions,
The required main function
The programmer defined function addnum, which sums the two values.
The function main reads in two integer values, and assigns them to a and b.Then, main calls addnum,
transferring the integer values a and b receiving their sum. The sum is then displayed and the program
terminates.
The integer values are transferred via the arguments num1 and num2,and their sum tot is returned to the
calling portion of the program via the return statement.
____________________________________________________________________

Types of functions u can refer ppt

Storage Classes
Storage class in c language is a specifier which tells the compiler where and how to store variables, its
initial value and scope of the variables in a program. Or attributes of variable is known as storage class
or in compiler point of view a variable identify some physical location within a computer where its
string of bits value can be stored is known as storage class.
The kind of location in the computer, where value can be stored is either in the memory or in the
register. There are various storage class which determined, in which of the two location value would be
stored.
Syntax of declaring storage classes is:-
storageclass datatype variable name;
There are four types of storage classes and all are keywords:-
1 ) Automatic (auto)
2 ) Register (register)
3) Static (static)
4 ) External (extern)
Examples:-
auto float x; or float x;
extern int x;
register char c;
static int y;

Compiler assume different storage class based on:-


1 ) Storage class:- tells us about storage place(where variable would be stored).
2) Intial value :-what would be the initial value of the variable.
If initial value not assigned, then what value taken by uninitialized variable.
3) Scope of the variable:-what would be the value of the variable of the program.
4) Life time :- It is the time between the creation and distribution of a variable
or how long would variable exists.

1. Automatic storage class


The keyword used to declare automatic storage class is auto.
Its features:-
Storage-memory location
Default initial value:-unpredictable value or garbage value.
Scope:-local to the block or function in which variable is defined.
Life time:-Till the control remains within function or block in which it is defined.
It terminates when function is released.
The variable without any storage class specifier is called automatic variable.
2. Register storage class
The keyword used to declare this storage class is register.
The features are:-
Storage:-CPU register.
Default initial value :-garbage value
Scope :-local to the function or block in which it is defined.
Life time :-till controls remains within function or blocks in which it is defined.
Register variable don’t have memory address so we can’t apply address operator on it. CPU register
generally of 16 bits or 2 bytes. So we can apply storage classes only for integers, characters, pointer
type.
Variable stored in register storage class always access faster than,which is always stored in the memory.
But to store all variable in the CPU register is not possible because of limitation of the register pair.
And when variable is used at many places like loop counter, then it is better to declare it as register
class.
Example:-
main( )
{
register int i;
for(i=1;i<=12;i++)
printf(“%d”,i);
}
3 Static storage class
The keyword used to declare static storage class is static.
Its feature are:-
Storage:-memory location
Default initial value:- zero
Scope :- local to the block or function in which it is defined.
Life time:- value of the variable persist or remain between different function call.

External storage classes


The keyword used for this class is extern.
Features are:-
Storage:- memory area
Default initial value:-zero
Scope :- global
Life time:-as long as program execution remains it retains.
Declaration does not create variables, only it refer that already been created at somewhere else. So,
memory is not allocated at a time of declaration and the external variables are declared at outside of all
the function.
INTRODUCTION
A Structure is a derived type usually representing a collection of variables of same or different data
types grouped together under a single name. The variables or data items in a structure are called as members
of a structure. A structure may contain one or more integer variables, floating-point variables characters
variables, arrays, pointers, and even other structures can also be included as members. Structures help to
organize data, particulary in large programs, because they allow a group of related variable to be treated as a
single unit.

There are two fundamental differences between structures and arrays.

1.An array demands a homogeneous data type, i.e., the elements of an array must be of the same data type,
where as structure is a heterogeneous data type, since it can have any data type as its member.

2.The difference is that elements in an array are referred by their positions, where as members in a structure
are referred by their unique name.

DECLARING A STRUCTURE

A structure within a C program is defined as follows:


struct struct-type
{

member-type1 member-name1;
member-type2 member-name2;
………
……….

Where
struct->is a keyword
struct type->is a name (tag) that identifies structures of composition member-type1
member name1.member-type2 member name2…are individual declaration.

Unlike the declaration of a variable of array, defining a structure causes no storage to be


reserved.

By defining a structure the programmers derives a new data type composed of a collection of
already known data types and their name. For example, suppose that the information about 10000
business accounts has to be maintained. The information consists of mixed data types, where for each
account the following are required.

EXAMPLE
account number (int)
account type (short)
name (30 char array)
street address (30 char array)
city/state/zip (30 char array)
balance long
last payment (long)
date

struct account
{
int acct_no;
short acct_type;
char name[30];
char street[30];
char city_state[30];
long balance;
long last_payment;
};

DEFINING A STRUCTURE
Declaring a structure is just a skeleton it merely describes the template. It does not reserve
any memory space rather than the declaration creates a new data type. To use the structure you have
to define it. Defining a structure means creating variables to access the members in the structure.
Creating a structure variable allocates sufficient memory space to hold all the members of the
structure. Structures variables can be created during structure declaration or by explicitly using the
structure name.

SYNTAX
struct <structure-name>
{
data type member1;
data type member2;
data type member3;
:
:
data type member;
}structure variable(s);

EXAMPLE

struct employee
{
int empno;
char empname[15];
float salary;
}emp1

Where the structure employee declares a variable empl of its type.


The structure variable(s) are declared like an ordinary variable is used to access the members of the
structure. More than one structure variable can also be declared by placing a comma in between the
variables.
Once the composition of the structures has been defined, individual structures variables can be
declared as follows: storage class struct struct_type variable 1, variable2… variable;
A variable of the above type id declared like this: struct account. Where the variable name is
customer and the data type is struct account. It is also possible to define a structure and declare a
variable of that at the same time:

SYNTAX

Storage-class struct struct-type


{
member_type1 memebr_name1;
member_type2 memebr_name2;
member_type3 memebr_name3;
………..
member_typen memebr_namen;
}
variable1, variable2….variable n;

The following figure shows the memory allocation of structure shown in the following figure:
empno 2 bytes
empname 15 bytes

Salary 4 bytes

NOTE

The keyword struct is optional when defining the structure using the structure name.

INITIALIZING A STRUCTURE

Similar to initialization of arrays, we can initialize structure variables also. The initializing a structure
variable expressed is expressed as:

SYNTAX

struct <structure_name>
{
data type member1;
:
:
:
data type member;
}structure_variable={value1,value2,…..valueN};

EXAMPLE

struct employeedet
{
int height;
float weight;
}emp1={165,60};

the above initialization initializes 165 to the structure member height and 60 to the structure member
weight. The value to be initialized for the structure members must be enclosed within a pair of
braces.

NOTE

The constants to be initialized to the structure members must be in the same order in which the
members are declared in the structure.

Write a program to initializing a structure using the structure name.


#include<stdio.h>
struct emp
{
int empno;
char name[20];
float salary;
};
void main()
{
struct emp e1,e2;
int size;
printf("Enter empno,name and salary \n");
scanf("%d %s %f",&e1.empno,e1.name,&e1.salary);
size=sizeof(e1);
printf("\n No. of bytes required for e1=%d \n\n",size);
e2=e1;
printf("After assigning e1 to e2 \n\n");
printf("e2.empno=%d \n",e2.empno);
printf("e2.name=%s \n",e2.name);
printf("e2.salry=%8.2f \n\n",e2.salary);
printf("Address of 1= %u \n",&e1);
//getch();
} Sample Program Output
Enter empno, name and salary
123 Nishu 3456
No. of bytes required for e1=26
After assigning e1 to e2
e2.empno=123
e2.name=Nishu
e2.salry=3456.00
Address of e1=65498
e1 and e2 are declared to be variables of struct emp type. Both can accommodate details of an
employee. Details of an employee are accepted into the variable e1.The number of bytes occupied by
a variable of struct emp type is found out with the help of the operator sizeof() by passing e1 to it.
The value returned by sizeof() is then displayed. To illustrate the fact that structure variables
assignment is permissible, e1 is assigned to e2.The contents of e2 are then displayed. The address of
operator & is used with e1 to obtain its address and it is then displayed.

OPERATIONS ON STRUCUTRES

The number of operations which can be performed over structures is limited. Following are the
permissible operations:

1. Accessing the individual members of a structure variable with the help of members operator (using
dot operator)

EXAMPLE

In the case of a variable of type struct emp,


struct emp e;
e.empno=10;
10 are assigned to empno number of e.
strcpy (e.name,”Kavi”);
The string “Kavi” is copied to name number of e.

2. Assigining one structure variable to another of the same type.


struct emp e1={12,”Kamal”,4000},e1
e2=e1;
e1 has been assigned to e2.

3. Retrieving the size of a structure variable using sizeof() operator.


struct emp e
int e;
s=sizeof(e);
Union is a concept similar to a structure with the major difference in terms of storage.
In the case of structures each member has its own storage location, but a union may contain
many members of different types but can handle only one at a time. Thus unions are used to
observe memory. They are useful for application involving multiple members. Values need not
be assigned to all the members at one time. Like structures union can be declared using the
keyword union as follows.
SYNTAX
union tag_name
{
data-type member1;
data-type memebr2;
:
:
data-type member n;
}

Where
union->is a keyword.
tag-name->is any user-defined name, which should be valid C identifier.
data-type->is any valid data type supported by C or user-defined type.
member1,member2…member->are the members of the union

The syntax of declaring a variable of union type is:

union tag_name variable_name;

A memory location gets allocated, the size of which is equal to that of the largest of the members
member1,member2,member3,…..member n.Accessing the members of a union is similar to
accessing the members of a strucute.Dot operator is used to access each individual member. Dot
operator expects union variable to its left and member name to its right.

EXAMPLE 1
union item
{
int m;
float p;
char c;
}
code;

union item makes a group of three data items of type int, float and char.

union item t;

A variable t declared to be of type union temp. As a result of this; only one memory location
gets allocated. It can be referred to by any one individual member at any point of time. The size
of the memory location is four bytes, which happens to be the size of the largest sized data type
float in the member list.

Example 2
Union var

{
Int m;
Char c;
Float a;
}
Union var x;

Now x is a union containing three members m,c,a. But only one value can be stored
either in x.m, x.c or x.a

DIFFERENCE BETWEEN STRUCTURE AND UNION

1. A structure is a user defined datatype available in C that allows to combine data items of
different kinds.
Union is also a user defined datatype that allows for storing different data types in
the same memory locations. We can define a union with many members, but only one
member can contain a value at any given time.

2. Keyword used is struct it defines a structure.


Keyword used is union

3. Members of structure do not share memory. So a structure need separate memory space
for all of its members.
Union shares the memory space among its members.So no need to allocate memory
to all members.

4. All members of structure can be initialized.


In union Only the first members can be initialized.

5. Size of structure is greater than or equal to sum of the each members size.
Size of union is equal to the size of the members having greater size.

6. In structures individual members can be accessed at a time.


In Union only one member can be accessed at a time.

You might also like