Sunday, November 23, 2008

Structure and Union Question C Programming with Solution of

Structure is user defined data type .It is tool by which we can store the data of different type like int ,float, char etc in single record. In array we can store only same type of data but structure encapsulates different data type variable in single record.
Syntax:
Struct [
]
{
[
];
[
];
[
];
………………………………………………….
………………………………………………….
} [
];

Here label which has written inside the [ ] are optional.

Example:
struct book
{
char *title;
int page;
int pub_year;
float price;
}book1,book2;

How to access the structure members?
Ans:
We can access the structure member with the help of . or -> operator.
First declare any structure variable:
struct book list;
Now to access any member variable write :
Structure.variable .member_variable
Example

list.title=”C programming”;
list.price=300.0;
If structure variable is pointer type then use ->
Example:
struct *list;
list->title=”C programming”;
list->price=300.0;
note : -> is similar to (*) .
so you can write (*list).price=300.0;

Instead of writing srtuct book we can give a simple name by typedef keyword
e.g typedef struct book BOOK;
BOOK *list;
list->page=400;
Or
(*list).page=400;

Member of structure are bounded to each other i.e if we sort only one member like year then automatically other member variable like title, price etc will sort.
Program:
void main()
{
int i,j;
struct book
{
char *title;
int page;
int pub_year;
float price;
};
struct book list[3],k;
//inserting the data
list[0].title="C programming";
list[0].page=300;
list[0].pub_year=1965;
list[0].price=410;
list[1].title="C coding";
list[1].page=270;
list[1].pub_year=1802;
list[1].price=200;
list[2].title="Advance c";
list[2].page=410;
list[2].pub_year=1993;
list[2].price=600;
//output before sorting

printf("TITLE\t\tPAGE\tPUB.\tPRICE\n\n");
for(i=0;i<3;i++) i="0;i<3;i++)" j="0;j

{
if(list[j].page>list[j+1].page)
{
k=list[j];
list[j]=list[j+1];
list[j+1]=k;
}
}
}
printf("After sorting of only page\n\n\n");
for(i=0;i<3;i++)>
 printf("%s\t%d\t%d\t%f",list[i].title,list[i].page,list[i].pub_year,list[i].price); 
printf("\n\n"); } 
getch(); 
}
Output: Initialization of structure member variable:
Example:
void main()
{
struct account
{
int id ;
float balance;
};
struct account customer1={100,50000.0};
struct account customer2={ 1001,3000.0};
………………………………………….
……………………………………..
}
Rule1. Order and type of value must match to the member variable. Struct account customer2={5000.0,102}; //wrong initialization
Rule 2. Default value of member variable is if int the 0 ,if float then 0.0 and if char then ‘\0’
Rule 3: First value is initialized to first member function of structure and so on;
Program:
void main()
{
int i,j;
struct book
{
char *title;
int page;
int pub_year;
float price;
};
struct book book1={"c programming"};
clrscr();
printf("%s\t%d\t%f",book1.title,book1.page,book1.price);
getch();
}
Output: c programming 0 0.000000
Explanation: First value is “c programming” is initialize to first structure member i.e title and rest structure members are initialized by its default value.
Note: If there are two variable of same structure then we can assign value of one structure variable to another structure variable like normal variable but if there is two structure variable of two similar type of structure then we cannot assign one variable to another variable.
Example:
void main()
{
int i,j;
struct book
{
char *title;
float price; };
struct magazine {
char *title;
float price;
};
struct book book1={"Programming",40.50},book2;
struct magazine magazine1;
book2=book1;
clrscr();
printf("%s\t%f",book2.title,book2.price); /* magazine1=book1; // It is wrong printf("%s\t%f",magazine1.title,magazine1.price); */
getch(); }

Output: Programming 40.500000
Program:
void main()
{
int i,j;
struct book
{
char *title;
float price; };
struct book book1={"Programming",40.50},book2;
book2=book1;
if(book1==book2) prinf("I Don't know structure");
else
printf("I Know structure");
getch();
}
Output: Compiler error Why we cannot use relation and logical operators in structure variable?
Ans: To store any type of data in structure there is minimum fixed byte which must be reserved by memory. This minimum byte is known as word boundary. Word boundary depends upon machine. TURBO C is based on 8086 microprocessor which has two byte word boundary. So any data type reserves at least two byte space. Suppose a structure word1: struct word1 {
char a;
int b;
char c;
};
First of all char a will reserve two byte and store the data in only first byte (size of char is one byte).Now int b(size of int two byte) will search two byte but there only byte is available so it will again reserve next two byte of memory space. That one byte will useless, such useless byte is know as slack byte and structure is called unbalance structure.
How we can make structure word1 as a balance structure?
Ans:
strcut word2
{ char a;
char b;
int c;
First of all char a will reserve two byte and store the data in only first byte .Now char b will search one byte and one byte is available so it will store the data in that byte. Now int c will reserve two byte and store the data in both two bytes. Now there is not any slack byte and we have saved wastages of memory and structure word2 is balance. 
(Before executing this program first go to option menu then compiler then code generation then select word alignment then press ok)

Program: 
void main() 
{
 struct word1 
{ char a; 
int b;
 char c;
 } ; 
struct word2 
{ char a; 
char b; 
int c; };
 clrscr(); 
printf("%d\t%d",sizeof(struct word1),sizeof(struct word2));
 getch();
 } 
Output: 6 4 Power of structure: Nesting of structure is possible. Bit level programming: Bit field: There are number of questions which have only two answers. To store such type of data there is necessity of only one bit either 0 or 1. Maximum child of any person must be less than 15. So for this four binary bit is sufficient to store such information. C introduces a powerful tool bit level programming in which we can store data which size can be in bit. So there is not necessity to declare int or char data type for only one or two bit data. In this way we can save the memory space.
 Syntax: 
Struct
{
name1:bit_length;
name2:bit_length;
…………………………………………………………………………
…………………………………………………………………………
};

must be signed or unsigned int
If it signed int then minimum bit length must be two, one for sign and another for data.
Example:
void main()
{
struct employee
{
unsigned id: 8;
unsigned sex:1;
unsigned age:7;
};
struct employee emp1={203,1,23};
clrscr();
printf("%d\t%d\t%d",emp1.id,emp1.sex,emp1.age);
getch();
}
Output: 203 1 23
We can access the data member in same way.
How bit data is stored in the memory:
Minimum size of structure which data member in bit is two byte i.e 16 bit.This is called word size of microprocessor. Word size depends on microprocessor. Turbo c is based on 8086 microprocessor which word size is two byte.

Bits are filed in from right to left direction 8 bit for id,1 bit for sex and 7 bit for age.
Important point:
1. If the sum of total bit length is 16 or less than 16 then size of structure will be two byte and if is greater than 16 and less than equal to 32 then size of strcture will be 4 byte and so on. Size must be multiple of two byte.
Program:
void main()
{
struct bitfield
{
signed int a:3;
unsigned int b:13;
unsigned int c:1;
};
struct bitfield bit1={2,14,1};
clrscr();
printf("%d",sizeof(bit1));
getch();
}
Output: 4
2.
Largest value can be stored in the n bit of bit length: 2^ (n-1)
If bit length is 4 then largest value it can store=2^3=8 otherwise its output will some difference.
3.We cannot take address of bit type variable so we can use scanf function.
4.There can be unused bit in word.
5. At same time member of structure can be normal data type (int,char,float,…) and bit type data.
Example:
void main()
{
struct bitfield
{
unsigned a:3;
char b;
unsigned c:5;
int d;
}bit;
clrscr();
printf("%d",sizeof(bit));
getch();
}
output: 5
Note: (Actual output will 6 due to slack byte ,So Before executing this program first go to option menu then compiler then code generation then select word alignment then press ok)


Good program:
What will be output:
void main()
{
struct bitfield
{
unsigned a:5;
unsigned c:5;
unsigned b:6;

}bit;
char *p;
struct bitfield *ptr,bit1={1,3,3};
p=&bit1;
p++;
clrscr();
printf("%d",*p);
getch();
}
Output: 12
Explanation:
Binary value of a=1 is 00001 (in 5 bit)
Binary value of b=3 is 00011 (in 5 bit)
Binary value of c=3 is 000011 (in 6 bit)
In memory it is represented as:

Let address of bit1 is 500 which initialize to char pointer p. Since can is one byte data type so p++ will be 501. *p means content of memory location 501 which is (00001100) and its binary equivalent is 12. Hence output is 12.
Misuse of pointer in structure:
What will be output?
void main()
{
struct field
{
int a;
char b;
}bit;
struct field bit1={5,'A'};
char *p=&bit1;
*p=45;
clrscr();
printf("\n%d",bit1.a);
getch();
}
Output: 45
2.Nesting of strcture:

Nesting of structure is possible i.e we can declare a strcture within another strcture but it is necessary inner strcture must declares strcture variable otherwise we can not access the data member of inner strcture.
Example:
void main()
{
struct world
{
int a;
char b;
struct india
{
char c;
float d;
}p;
};
struct world st ={1,'A','i',1.8};
clrscr();
printf("%d\t%c\t%c\t%f",st.a,st.b,st.p.c,st.p.d);
getch();
}
Output: 1 A I 1.800000
2. Structure member data type can be array, structure (not same strcture) or union.
void main()
{
struct india
{
char c;
float d;
};
struct world
{
int a[3];
char b;
struct india orissa;
};
struct world st ={{1,2,3},'P','q',1.4};
clrscr();
printf("%d\t%c\t%c\t%f",st.a[1],st.b,st.orissa.c,st.orissa.d);
getch();
}
Output : 2 p q 1.400000



UNION: union is user defined data type which stores different type of data in common memory location.
Syntax:
Union [
]
Data type
;
Data type
;
………………………………………………………………..
………………………………………………………………….;
}[
];

[ ] indicates they are opyional;
Example :
void main()
{
union world
{
int a;
char b;
float c;
};
union world uk;
clrscr();
printf("%d",sizeof(uk));
getch();
}
Output: 4
Explanation:

Data member of union uses common(or share) memory space.Size of union is always a data member of union which has largest size. Here float c has largest size so size of union is 4.
Important point:
1.In union only first member is active so we can initialize only first member. Rest member variable will assign a value which is store in share memory location.
Example:
void main()
{
union world
{
int a;
char b;
char c;
};
union world uk={5000};
char *ptr;
ptr=(char *)&uk;

clrscr();
printf("%d\t%d ",*ptr,uk.b);
getch();
}
Output :
-120 -120
Explanation:
Size of union will be 16 bit (int a has largest size which is 2 byte).Its active member is variable a, so a will assign value 5000.
Binary value of 5 is 1001110001000

which is represented in memory:
Let memory address of uk is 500 so ptr is pointing to the memory location 500. *ptr means content at location 500 which is 10001000.
Since its signed bit 1 so number is negative and negative number is stored in the memory in 2’scomplement format.

Decimal value of 1111000 is 120. Hence *ptr will -120. char b also uses same memory location i.e 500 So output of uk.b will be also -120.

3. Member of union can be union (not same), structure or array.

4. Nesting of union is possible i.e we can declare a union inside the other union.
Structure and union can do any thing:
System Level programming.
In this section you will know power of structure and union.In the header file
there are two important structures and union (Remember this structure)

1. struct BYTEREGS {
unsigned char al, ah, bl, bh;
unsigned char cl, ch, dl, dh;
};

2.struct WORDREGS {
unsigned int ax, bx, cx, dx;
unsigned int si, di, cflag, flags;
};

3.union REGS {
struct WORDREGS x;
struct BYTEREGS h;
};
In
there is function int86().IT general 8086 software interrupt interface. It will better to explain it by an example.

Write a c program to display mouse.
Ans:

#include

#include

void main()
{
union REGS i,o;
i.x.ax=1;
int86(0x33,&i,&o);
getch();
}

Explanation: To write such program interrupt table is necessary.

It is a small part of interrupt table. It has four field input,output,service number and purpose ,
Now see the first line which is inside the rectangle. To display the mouse pointer assign ax equal to 1 i.e service number while ax is define in the WORDREGS

struct WORDREGS {
unsigned int ax, bx, cx, dx;
unsigned int si, di, cflag, flags;
};

and WORDRGS is define in the union REGS


union REGS {
struct WORDREGS x;
struct BYTEREGS h;
};
So to access the ax first declare a variable of REGS i.e

REGS i,o;
To access the ax write i.x.ax (We are using structure variable i because ax is input,see interrupt table)
So to display mouse pointer assign the value of service number:
i.x.ax=1;
To give the this information to microprocessor
We use int86 function.It has three parametr
1. interrupt number i.e 0x33
2. union REGS *inputregiste i.e &i
3. union REGS *outputregiste i.e &o;
So write : int86(0x33,&i,&o);


Interrpt table with interrupt number and purpose

Q.Write a c program which restrict the movement of pointer?
Ans:
//restric the x and y cordinate
#include

#include

void main()
{
union REGS i,o;
//show mouse pointe
i.x.ax=1;
int86(0x33,&i,&o);
//x cordinate restiction
i.x.ax=7;
i.x.cx=20;
i.x.dx=300;
int86(0x33,&i,&o);
//y cordinate restriction
i.x.ax=8;
i.x.cx=50;
i.x.dx=250;
int86(0x33,&i,&o);
getch();
}

Q.Write c program which display position of pointer in (x coordinate,y coordinate)?
Ans:
#include

#include

void main()
{
union REGS i,o;
int x,y,k;
//show mouse pointe
i.x.ax=1;
int86(0x33,&i,&o);
while(!kbhit()) //its value will false when we hit key in the key bord
{
i.x.ax=3; //get mouse position
x=o.x.cx;
y=o.x.dx;
clrscr();
printf("(%d , %d)",x,y);
delay(250);
int86(0x33,&i,&o);
}

getch();
}
Q.Write a c program which changes the position of cursor?
Ans:
#include

#include

void main()
{
union REGS i,o;
i.h.ah=2; //positioning the cursor
i.h.bh=0;
i.h.dh=30;
i.h.dl=45;
int86(0x10,&i,&o);
printf("World");

getch();
}
Q.Write a c program to creat a directory in current working directoty?
Ans:
#include

void main()
{
union REGS i,o;
i.h.ah=0x39;
i.x.dx="ravan";
int86(0x21,&i,&o);
getch();
}

Q.Write the c program to switch the 256 color graphics mode.
Ans:
#include

#include

void main()
{
int x,y,b;
union REGS i,o;
i.h.ah=0;
i.h.al=0x13;
int86(0x10,&i,&o);
getch();
}
Q.Write a c program to create a simple paint brush deginer ?
Ans:
#include

#include

#include

#include

void main()
{
int x,y,b,px,py,c,p,s,cl;
int d=0,m;
union REGS i,o;
initgraph(&d,&m,"c:\tc");
i.x.ax=1;
int86(0x33,&i,&o);
i.x.ax=8;
i.x.cx=20;
i.x.dx=450;
int86(0x33,&i,&o);
printf("Brush style insert number from 0 to 5 : ");
scanf("%d",&p);
printf("Brush size insert number from 1 to 7 : ");
scanf("%d",&s);
printf("Brush color insert number from 1 to 16 : ");
scanf("%d",&cl);
clrscr();
cleardevice();
printf("\t\t**********DRAW IMAGE************");
while(!kbhit())
{
i.x.ax=3;
b=o.x.bx;
x=o.x.cx;
y=o.x.dx;
px=x;
py=y;
int86(0x33,&i,&o);
if(cl==16)
{
c=random(16);
}
else
{
c=cl;
}
setcolor(c);
if(b==1)
{
i.x.ax=3;
int86(0x33,&i,&o);

x=o.x.cx;
y=o.x.dx;
b=o.x.bx;
switch(p)
{
case 1:circle(px,py,s);break;
case 2:ellipse(px,py,0,270,s,s+2);break;
case 3:fillellipse(px,py,s+2,s);break;
case 4:rectangle(px,py,x,y);break;
case 5:sector(px,py,30,120,s,s);break;
default:line(px,py,x,y);
}
}
}

getch();
restorecrtmode();
closegraph();
}


No comments:

Blog List