structures. library system : book’s name (a string), book’s price (a float) number of pages in...

Post on 19-Jan-2018

219 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

main( ) { char name[3] ; float price[3] ; int pages[3], i ; printf ( " Enter names, prices and no. of pages " ) ; for ( i = 0 ; i

TRANSCRIPT

STRUCTURES

Library system :Book’s name (a string), Book’s price (a float)number of pages in it (an int).

SOLUTION- Construct individual arrays, one for storing

names, one for storing prices, one for storing number of pages.

Use a structure variable.

main( ){char name[3] ;float price[3] ;int pages[3], i ;printf ( "\nEnter names, prices and no. of pages\n" ) ;for ( i = 0 ; i <= 2 ; i++ )scanf ( "%c %f %d", &name[i], &price[i], &pages[i] );printf ( "\nAnd this is what you entered\n" ) ;for ( i = 0 ; i <= 2 ; i++ )printf ( "%c %f %d\n", name[i], price[i], pages[i] );}

Enter names, prices and no. of pagesA 100.00 354C 256.50 682F 233.70 512

And this is what you enteredA 100.000000 354C 256.500000 682F 233.700000 512

OUTPUT

STRUCTURE

A structure contains a number of data types grouped together.

These data types may or may not be of the same type.

DECLARATION A DATA STRUCTUREstruct book{char name[22] ;float price ;int pages ;} ;struct book b1

;

variables b1 can be declared to be of the type struct book

, b2, b3

struct <structure name>{structure element 1 ;structure element 2 ;structure element 3 ;............

} ;

struct employee{ char name ; int age ; float salary ;} ;struct employee e

Declarations & Definitions

= { ”Rahul”, 25, 4000.50 } ;

ORstruct employee{ char name[20] ; int age ; float salary ;

[20]

= { ”Rahul”, 25, 4000.50 } ;}e , x, y

MEMORY ALLOCATION struct book b1, b2, b3 ;

it makes available space to hold all the elements in the structure—

in this case, 7 bytes—one for name, four for price and two for pages.

These bytes are always in adjacent memory locations.

Copyingmain( ){ struct emp{ char n[20] ; int a ; float s ;

} ;struct emp e1 = { ”Rahul”, 23, 4000.50 } ;

struct emp e2, e3 ;e2.n = e1.n ;

e2.s = e1.s ;

strcpy ( ) ;

e3 = e1 ;printf ( ”%s %d %f”,e3.n, e3.a, e3.s ) ;

e2.a = e1.a ;

}

piecemealcopying

copying atone shot

e2.n, e1.n

Copying Arraysint a[10] = { 3, 6, 5, … } ;int b[10] ;for ( i = 0 ; i <= 9 ; i++ )

b[i] = a[i] ;

struct z a

b = a ;

struct z { int arr[10] ;} ;

struct z b ;

OR

= { 1,2,3,4,5,6,7,8,9,0 } ;

WAP TO DISPLAY SIZE OF STRUCTURE ELEMENTS. USE SIZEOF() OF OPERATOR.main(){

struct book1{char book[30];int pages;float price;};

struct book1 bk1;

printf(“\nSize of Structure elements\n”);printf(“\nBook: %d”,sizeof(bk1.book));printf(“\nPages: %d”,sizeof(bk1.pages));printf(“\nPrice:%d”,sizeof(bk1.price));printf(“\nTotal Bytes:%d”,sizeof(bk1));

}

OutputBook : 30Pages:2Price:4Total Bytes:36

struct result { int rno, mrks[3]; char nm; }res; void main() { int i, total=0; float per; printf("\n\t Enter Roll Number : "); scanf("%d",&res.rno); printf("\n\t Enter Marks of 3 Subjects : "); for(i=0;i<3;i++) { scanf("%d",&res.mrks[i]); total = total + res.mrks[i]; }

per= total/3; printf("\n\n\t Roll Number : %d",res.rno); printf("\n\n\t Marks are :"); for(i=0;i<3;i++) { printf(" %d",res.mrks[i]); } printf("\n\n\t Percentage is : %f %“,per); }

Enter Roll Number : 1 Enter Marks of 3 Subjects : 80 86 80

Roll Number : 1 Marks are : 80 86 80 Percentage is : 82.00 %

STRUCTURE WITH ARRAYS

struct emp_info { int emp_id; char nm[50]; }emp[2]; void main() { int i; for(i=0;i<2;i++) { printf("\n\n\t Enter Employee ID : ");

scanf("%d",&emp[i].emp_id); printf("\n\n\t Employee Name : "); scanf("%s",emp[i].nm); } for(i=0;i<2;i++) { printf("\n\t Employee ID :

%d",emp[i].emp_id); printf("\n\t Employee Name :

%s",emp[i].nm); } }

Enter Employee ID : 1 Employee Name : ABC Enter Employee ID : 2 Employee Name : XYZ Employee ID : 1 Employee Name : ABC Employee ID : 2 Employee Name : XYZ_

Nested Structuresmain( ){ struct address{

char city[20] ; long int pin;} ;

struct emp e = { ”Rahul”, 23,”Nagpur”,440010,4000.50 } ;

printf ( ”%s %d%s%ld%f”,e.n,}

struct emp{ char n[20] ;

e.age, e.pin,e.s ) ;

e.city,

int age ; float s ;struct address a ;

} ;

e.a.pina.citye.a.city

printf ( ”%d”, a.b.c.d.e.f ) ;

f - int

struct stud_Res { int rno; char std[10]; struct stud_Marks { char subj_cd[30]; int subj_mark; } marks; }result;

void main() {printf("\n\t Enter Roll Number : "); scanf("%d",&result.rno); printf("\n\t Enter Standard : "); scanf("%s",result.std); printf("\n\t Enter Subject Code : "); scanf("%s",result.marks.subj_cd); printf("\n\t Enter Marks : "); scanf("%d",&result.marks.subj_mark); printf("\n\n\t Roll Number : %d",result.rno); printf("\n\n\t Standard : %s",result.std); printf("\nSubject Code : %s",result.marks.subj_nm); printf("\n\n\t Marks : %d",result.marks.subj_mark); }

Enter Roll Number : 1 Enter Standard : F.Y.Enter Subject Code : SUB001 Enter Marks : 63 Roll Number : 1 Standard : F.Y..Subject Code : SUB001 Marks : 63_

main( ){ struct book{ char n[20] ; int nop ;float pr ;} ;struct book b = { ”Basic”, 425, 135.00 } ;

display (b.n,b.nop,b.pr ) ;show ( b.n,&b.nop,&b.pr ) ;}

display (char *n,int pg,float p ){ printf ( ”%s %d %f”, n, pg, p ) ;}show (char *n,int *pg,float *p ){ printf ( ”%s %d %f”, n, *pg, *p ) ; }

Passing Structure Elements

bb .n,( * )

main( ){ struct book{ char n[20] ; int nop ;float pr ;} ;struct book b = { ”Basic”, 425, 135.00 } ;

display1 ( b ) ;show1 ( &b ) ;}display1 ( )

{ printf ( ”%s %d %f”, }show1 ( ){ printf ( ”%s %d %f”,

}

Passing Structures

struct book bbbb.n,bb.nop,bb.pr ) ;

struct book *bb bb .nop,

bb .pr ) ;printf ( ”%s %d %f”, bb -> n ,bb -> nop,

bb -> pr ) ;

( * )( * )

main( ){ struct com { float r, i ;} ;

struct com a

c = add ( a, b ) ;

add ( struct com x, struct com y )

}

Complex Nos.

struct com c ;

x.r + y.r ;x.i + y.i ;

struct com b = { 1.2, 1.7 } ;

printf ( ”%f %f”, c.r, c.i ) ;

struct com add ( struct com, struct com ) ;

= { 2.5, 1.3 } ;

struct com add ( struct com x, struct com y ) {}

z.i = x.i + y.i ;z.r = x.r + y.r ; struct com z ;

return z ;

ASSIGNMENT 41- What is nesting of structures and union ?

2- What is sorting ? Write a program for insertion sort using pointers.

ADVANTAGES OF STRUCTURE Structure has several advantages:

It clarifies the code by showing that the data defined in the structure are intimately related.

It simplifies passing the data to functions. Instead of passing multiple variables separately, they can be passed as a single unit.

It increases the locality of the code.

20

POINTERS AND STRUCTURES The way we can have pointer pointing to an

int , or a pointer pointing to a char, similarly we can also have a pointer pointing to a struct.

Example :struct date { int month, day, year; }; struct date today, *date_ptr;

STRUCTURE POINTER OPERATOR “->” Pointers to structures are so often used in C

that a special operator exists. The structure pointer operator “->” It permits expressions that would otherwise

be written as, (*x).y to be more clearly expressed as x->y

EXAMPLE : STRUCTURE POINTERS main() {

struct date { int month, day, year; }; struct date today, *date_ptr;

date_ptr = &today; date_ptr->day = 11; date_ptr->month = 11; date_ptr->year = 2011; printf("Todays date is %d/%d/%d.\n",

date_ptr->day, date_ptr->month, date_ptr->year );

}

NOTE : STRUCTURE POINTERS Notice that the syntax date_ptr->day

is equivalent to (*date_ptr).day . The parentheses in this access are

required, because along with () and [], the operators ‘.’ and ‘->’ have the highest precedence and associate from left to right.

Therefore *date_ptr.day would be a syntax error because date_ptr.day can not be evaluated.

SELF-REFERENTIAL STRUCTURES

Self-referential structuresStructure that contains a

pointer to a structure of the same type

Can be linked together to form useful data structures such as lists, queues, stacks and trees

Terminated with a NULL pointer (0)

USE OF SELF-REFERENTIAL STRUCTURES Following is an example of this kind of

structure: struct struct_name

{       datatype datatypename;       struct_name * pointer_name;};

EXAMPLE : SELF-REFERENTIAL STRUCTURES struct listnode {

int data;struct listnode *next;

}; In the above example, the listnode is a self-

referential structure – because the *next is of the type sturct listnode.

EXAMPLE : SELF-REFERENTIAL STRUCTURES

2 3 NULL1listnode listnode listnode

*listnode*listnode

EXAMPLE : SELF-REFERENTIAL STRUCTURES Diagram of two self-referential structure

objects linked together

1015

NULL pointer (points to nothing)

Data member and pointer

PASSING STRUCTURE TO A FUNCTION… Structure variables may be passed as

arguments and returned from functions just like other scalar variables i.e. int , char.

EXAMPLE : PASSING STRUCTURE TO A FUNCTION… struct struct_type { int a, b;} ;

void f1(struct struct_type parm){  printf("%d", parm.a);}void main(void){  struct struct_type arg;  arg.a = 1000;  f1(arg); }

PROBLEM IN PASSING STRUCTURE… Here, a structure is passed to the function.

Recall that in C, all parameters are passed by value - the value of each argument expression is copied from the calling function into the cell allocated for the parameter of the called function. Again, for large structures, this may not be a very efficient way to pass data to functions.

REMEDY : PASSING STRUCTURE… passing and returning structures to functions

may not be efficient, particularly if the structure is large. We can eliminate this excessive data movement by passing pointers to the structures to the function, and access them indirectly through the pointers.

39

EXAMPLE : PASSING STRUCTURE TO A FUNCTION… struct struct_type { int a, b;} ;

void f1(struct struct_type *parm){  printf("%d", parm->a);}void main(void){  struct struct_type arg;  arg.a = 1000;  f1(&arg); }

40

EXAMPLE : RETURNING STRUCTURE FROM A FUNCTION…

struct struct_type { int a, b;} ;struct_type f1(int x){  struct struct_type param;  param.a = x; return param;

}void main(void){  struct struct_type arg;  arg = f1(1000); }

41

EXAMPLE : RETURNING STRUCTURE FROM A FUNCTION…

struct struct_type { int a, b;} ;struct_type *f1(int x){  struct struct_type *param;  param->a = x; return param;

}void main(void){  struct struct_type *arg;  arg = f1(1000); }

42

top related