"Algorithms + Data Structures Programs!": - Niklaus Wirth
"Algorithms + Data Structures Programs!": - Niklaus Wirth
- Niklaus Wirth
STRUCTURES
user defined data type.
Collection of variables refrenced under one
name.
in ‘C++’ has backward compatibility with ‘ C’.
Declared with the help of keyword ‘struct’.
All members are public by default .
Structure Declaration.
struct date
struct tag
{
{
int day;
type variable-name;
int month
type variable-name;
int year;
type variable-name;
};
:
}structure variables;
The ‘typedef ‘ Keyword.
as in
struct date
typedef struct date
{ int day ; { int day ;
int month;
int month;
}; };
D1.year=1988;
D2.day= 2;
.
struct_name element_name
da month year
y
D1 D1.yea
r
D2
D2.day
Structure Assignments.
Eg.
p2=n2;
//error: type
Complex Structures
Structure elements may be simple or complex.
Array of structures.
eg. Struct emp e[10];
Arrays within structure
eg. Struct student
{
char name[20];
int marks[5];
};
Nested Structures
Struct addr
structure within a structure
{ int houseno;
inner structure should be char locality[20];
defined before outer structure . char city[20];
Elements are refrenced };
outermost to innermost. Struct employee
Representation as in memory.
The Concept of BIT FIELDS
A bit field is a set of adjacent bits whose size varies from 1-16
bits in length.
15 14 13 12 …………………………… 2
1 0
struct personal
{ unsigned gender : 1 ;
Bit Bit Range
unsigned age : 7 ;
field length of
gender 1 values
0 or 1
unsigned mar_status : 1 ;
unsigned children : 3 ;
age 7 0 to 127
}emp; (27 – 1)
Martial 1 0 or 1
Emp.gender=1; status
Emp.age=32; children 3 0 to 7
(23 – 1)
Problems On Structures..
// as asked in various campus
placements //
This Question was asked at technical exam for IBM
Give the output of the following program .
Struct point a) 25:20
{int x,y;};
40:10
Void show(point p)
{cout<<p.x<<“:”<<p.y<<endl; } 35:10
Void main()
{ point U={20,10},V,W;
e) 25:20
V=U;
40:20
V.X+=20;
W=V; 35:10
U.Y+=10;
U.X+=5;
i) 25:10
W.X-=5;
show(U);show(V);show (W); 40:10
} 35:10
Solution
A) 25:20
40:10 X Y
Struct point
35:10
{int x,y;};
Void show(point p)
{cout<<p.x<<“:”<<p.y<<endl; }
U
Void main()
{ point U={20,10},V,W;
V=U;
V.X+=20;
V
W=V;
U.Y+=10;
U.X+=5;
W.X-=5;
show(U);show(V);show (W);
W
} ;
Aptitude test
Correct Ans is
D) NO error !
struct date {
short day;
short month;
short year ;
}bdate,joindate;
is also correct
Possible Questions for Technical interview.