Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

CS3251 Programming in C Notes

Uploaded by

rsviniba96
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

CS3251 Programming in C Notes

Uploaded by

rsviniba96
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 179

4.

1 STRUCTURE

INTRODUCTION

• C language provides a rich set of primitive and derived data types for the efficient storage and ma -
nipulation of data.

• Using C language new data types can be created. These data types are known as user-defined data
types and created by using structures, unions and enumerations.
• Arrays are used for storage of homogeneous data. They cannot be used for storage of data of dif-
ferent types.
• One of the similarities between array and structure is that both contains finite number of elements.
Thus array types and structure types are collectively known as aggregate types.

• Unions are similar to structures in all aspects except the manner in which their constituent ele -
ments are stored. In structures, separate memory is allocated to each element, while in unions, all
the elements share the same memory.
• Enumerations – for defining a data type whose objects can take a limited set of values.

NEED FOR STRUCTURE DATA TYPE / USES OF STRUCTURES

• It allows grouping together of different type of elements.


• Complex data types can be handled using nesting of structures
• Structures can be used to define records to be stored in files
• It gives flexibility to programmers to define their own data types as per the requirement.
• It is also possible to create structure pointers.

STRUCTURE
⮚ A structure is a collection of variables of different data types grouped under a single name.
⮚ Structures are defined as a collection of data items of different data types under a common
name. Structures are collection of related variables under one name.

Example:
Student: name, roll_no, marks

There are three aspects of working with structures.


1. Defining a structure(Creating a new type)
2. Declaring variables and constants of newly created type.
3. Using and Performing operations on objects of structure type.

STRUCTURE DEFINITION
● A structure definition consists of the keyword struct followed by an optional identifier name
known as structure tag-name and a structure declaration list enclosed within the braces.
● The structure declaration list consists of declarations of one or more variables, possibly of differ-
ent types. The variables declared inside the declaration list are known as structure members or
fields.

The general form of structure-type definition is

struct structure_name
{
type membername1;
type membername2;
…................
…................
};
Eg:
struct book
{
char title[25],author[25];
int pages;
float price;
};

● Structure definition can have an infinite number of members.

● After the definition of structure type, the keyword struct is used to declare its variables.
● A structure definition cannot contain an instance of itself. But it may contain a pointer to an in -
stance of itself. Such a structure is known as self-referential structure.
● A structure definition does not reserve any space in the memory.
● It is not possible to initialize the structure members during the structure definition.

Eg:
struct book
{
int pages=10; //Not valid
};

If a structure definition does not contain a structure tag-nam, then the created structured is un -
named. It is also known as anonymous structure type. The objects of anonymous type should be declared
only at the time of structure definition.

DECLARING STRUCTURE OBJECTS/VARIABLES

● Variables and constants of the created structure type can be declared either at the time of structure
definition or after the structure definition.

The general form of declaring structure object is

struct structure_name identifier[=initialization_list];

[=initialization_list] is optional.
(or)
struct struct_name v1,v2,....vn;
where v1,v2,..vn are variables
Eg:
struct book b1;
struct student s1,s2,stud;
A structure object declaration consist of
• The keyword struct for declaring structure variables.
• The tag name of the defined structure type.
• Comma separated list of identifiers
• A terminating semicolon.
EX :
struct book
{
char title[20]; //Defining a structure
int pages;
float price;
};
struct book b1,b2,b3; //Declaring structure variable
• It is also possible to combine both definition and variable declaration in one statement.

EX:

struct book
{
char title[20]; //Defining a structure
int pages;
float price;
}b1,b2,b3; //Declaring structure variable

• The objects of defined structure type cannot be declared without using the keyword struct.
• The amount of memory space allocated to it is equal to the sum of the memory space required by
all of its members.
• The structure members are assigned memory addresses in increasing order.
• The members of the structure object can be initialized by providing an initialization list. An initial -
ization list is a comma separated list of initializers.

Operations on structures
The operations that can be performed on an object of structure type can be classified into two
types.
1. Aggregate Operations
- operates on the entire operand as a whole.
2. Segregate Operations
- operates on the individual members of a structure object.

Aggregate Operations
There are four aggregate operations that can be applied on an object of a structure type.
1. Accessing members of an object of structure type
2. Assigning a structure object to a structure variable.
3. Address of a structure object.
4. Size of a structure.

Accessing members of an object of structure type


The members of a structure object can be accessed by
1. Direct Member Access operator (. dot operator).
2. Indirect Member Access operator (→ arrow operator).

Initialization of Structures

• The members of a structure can be initialized to constant values by enclosing the values to be as -
signed within the braces after the structure definition.
Syntax:
struct struct_name
{
member1;
member2;
.
.
.

}struct_variable={contant1, constant2,....};

(or)

struct struct_name struct_variable={contant1, constant2,….};


Ex:

struct date
{
int date;
int month;
int year;
}independence= {15,08,1947};
or
struct date independence={15,08,1947};

- Initializes the member variables date, month, year of independence to 15,08,1947 respectively.

Accessing Structure members.


- The members of the structures can be accessed by using the structure variable along with the
dot(.) operator.

Syntax:
variable name. member name;

Ex:
struct book
{
int id;
char name[20];
};
struct book b1;

For accessing the structure members from the above example.


b1.id;
b1.name; where 'b1' is the structure variable.

The structure can be defined either before main() as globally or inside main() locally.

Example program :
#include<stdio.h>
struct book //structure name
{
int id;
char name[20];
char author[15];
};
main()
{
struct book b1; // structure variable
printf(“\n Enter the book id, book name\n”);
scanf(“%d\n%s\n”,&b1.id,b1.name);
printf(“\n Book id is = %d”,b1.id); //Accessing structure member
printf(“\n Book name is = %s”,b1.name);
}

output:
Enter the book id, book name
101
Maths
Book id is = 101
Book name is = Maths
4.2 NESTED STRUCTURES (STRUCTURE WITHIN A STRUCTURE)

• A structure can be declared within another structure.


• Some times it is required to keep a compound data items within another compound data item is
called structure within structure or it means nesting of structures.
Syntax :

struct struct_name1
{
decl 1;
decl 2;

.…
decl n;
};
struct struct_name2
{
decl 1;
decl 2;
struct struct_name1 variable_name1; //structure within structure
.....
decl n;
};

Example Program :
#include<stdio.h>
struct date
{
int date, month, year;
};
struct stu_data
{
char name[20];
struct date dob;
};
main()
{
struct stu_data s ={“vinoth”,{01,03,82}};
printf(“\n Name %s”,s.name);
printf(“\n \n Date of birth : %d-%d-%d”,s.dob.date, s.dob.month, s.dob.year);
getch();
Return;
}

Output :
Name : Vinoth
Date of Birth : 01- 03- 82
4.4 ARRAYS OF STRUCTURES

• The C language permits to declare an array of structure variable.


• If we want to handle more records within one structure, we need not specify the number of struc-
ture variable.
• In such cases we declare an array of structure variable to store them in one structure variables.

Syntax:

struct struct_name
{
decl1;
decl2;
......
decl;
}variable_name[size];

Example :
struct marks
{
int subject1;
int subject2;
int subject3;
};
main()
{
struct marks student[3]={{95,92,89},{65,63,70},{87,76,61}};
}

Differences between Array and Structure

Array Structure
An array is a collection of related data ele- Structure can have elements of different
ments of same type. types.
An array is derived data type structure is a user-defined one
Any array behaves like a built-in data type It must be declared and defined
An array can be increased or decreased A structure element can be added if neces-
sary.
4.9 UNION

 Union is a collection of variables of different data types.


 Union is also a derived data type which is used to represent dissimilar data items.
 Unions are used to create user-defined types.
 Declaration and definition of union are same as structure, but use the keyword 'union' instead of 'struct'.
 The structure and union differs in terms of storage.
 In structure, a separate memory is allocated to each member, while in unions, all the members of union
share the same memory.

Characteristics of union:
 Members of union have same memory location.
 Collection of variables of different data types.
 The keyword 'union' is used to declare a union.
 Members of the union can be accessed using the dot operator.
 Size allocated is equal to the largest data member of the union.
 Only one union member can be accessed at a time.
 The members of a union are stored in the memory in such a way that they overlap each other.

Definition and Declaration of Union


 A union definition consists of the keyword union followed by an optional identifier name and the
union declaration list enclosed within the braces.
 A union object declaration consist of
 The keyword union for declaring union variables.
 The tag name of the defined structure type.
 Comma separated list of identifiers
 A terminating semicolon.
Syntax :

union union_name
{
union member1;
union member2;
.....
union member n;
};
union union_name variable;

Eg :
union numbers
{
char a;
int b ;
float c;
}r;

Memory Allocation in Union:

char a
int b
float c
Address
2000 2001 2002 2004
Example program :
Employee details using Union.

#include<stdio.h>
#include<conio.h>
union employee
{
char name[10];
int idno;
float salary;
}e;
main()
{
printf(“Enter the name\n”);
scanf(“%s”,e.name);
printf(“Enter the id number\n”);
scanf(“%d”,&e.idno);
printf(“Enter the salary\n”);
scanf(“%f”,&e.salary);

printf(“Name : %s\n”,e.name);
printf(“Id number : %d\n”,e.idno);
printf(“Salary : %f\n”,e.salary);

getch();
return;
}

Output :

Enter the name


Ram
Enter the id number
101
Enter the salary
20000
Name : Ram
Id number : 101
Salary : 20000

Differences between Structure and Union

S.NO Structure Union


1 It occupies its own memory space. It uses the same space.
2 The keyword 'struct' is used. The keyword 'union' is used.
3 All members of a structure can be initialized. Only the first member of a union can be
initialized.
4 Each member is stored in a separate memory All members are stored in the same memory
locations. location.
5 More memory space is required. Less memory space is required.

You might also like