chapter 6 structures

62
Chapter 6 Structures By C. Shing ITEC Dept Radford University

Upload: reuben-delaney

Post on 03-Jan-2016

23 views

Category:

Documents


0 download

DESCRIPTION

Chapter 6 Structures. By C. Shing ITEC Dept Radford University. Objectives. Understand how to use structures Understand how to call function by passing structures Understand how to use unions. Structure. A record that can store different data types - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 6 Structures

Chapter 6 Structures

By C. Shing

ITEC Dept

Radford University

Page 2: Chapter 6 Structures

Slide 2

Objectives Understand how to use structures Understand how to call function by passing

structures Understand how to use unions

Page 3: Chapter 6 Structures

Slide 3

Structure A record that can store different data types Declared data type (struct structure_name) first as

struct [structure_name] {type1 fieldname1;… } [variable_lists];

Then define a new type by typedef struct structure_name structure_type;or typedef struct {

type1 fieldname1;… } structure_type;

Page 4: Chapter 6 Structures

Slide 4

Structure (Cont.)

Example:

struct student_record {

char lastname[30];

char firstname[15];

float gpa; };

typedef struct student_record student_rec;

Page 5: Chapter 6 Structures

Slide 5

Structure (Cont.) Declared variables then as

struct structure_name variable_list; Or use

structure_type variable_list;

Example:

struct student_record student1, student2;

struct student_record student[100];

or

student_rec student[100];…

Page 6: Chapter 6 Structures

Slide 6

Initialize Structure Similar to initialize an array Fill in 0 or NULL if not enough data

Example:

student_rec student1={“Doe”, “John”, 2.0};

student_rec student_any;

Page 7: Chapter 6 Structures

Slide 7

Read in Structure from Keyboard Example:

scanf(“%s%s%f”, student1.lastname,

student1.firstname, &student1.gpa);

// data: Doe John 2.0

Example1

Page 8: Chapter 6 Structures

Slide 8

Structure Assignment Assign field:

student_any.lastname=student1.lastname;

Example: Program, Data Assign whole structure:

Example:

student_any= student1;

Page 9: Chapter 6 Structures

Slide 9

Pointer and Structure If a pointer p to a stucture_type variable, then

to access a field (or member), use p -> fieldname

Or (*p).fieldname

Example 2

Page 10: Chapter 6 Structures

Slide 10

Pointer and Structure (Cont.)Example:

student_rec student1={“Doe”, “John”, 2.0},*student_pointer=&student1;

Then student_pointer->lastname = “Doe”; (*student_pointer).firstname = “John”; student_pointer->gpa=2.0; (student_pointer->firstname)[3]=‘n’; (*(student_pointer->firstname))+2=‘L’;

Page 11: Chapter 6 Structures

Slide 11

Pass Structure to Function Use pass-by-value: pass a copy of structure,

Default, not efficient If structure is changed after function call, must return the structure_type result The returned result must be assigned back to the original variable

Example: student1=change_gpa (student1);

student_rec change_gpa (student_rec student_any) { printf(“Please enter new gpa:\n”); scanf(“%f”, &student_any.gpa); return student_any; }

Example 3

Page 12: Chapter 6 Structures

Slide 12

Pass Structure to Function (Cont.) Use pass-by-reference: pass in pointer,

very efficient

Example: change_gpa (&student1);

void change_gpa (student_rec *student_pointer) { printf(“Please enter new gpa:\n”); scanf(“%f”, &student_pointer->gpa); }

Example 4

Page 13: Chapter 6 Structures

Slide 13

Sort Structures Problem: input data into array of structures And then sort themData:1 15.0 2 15.03 11.04 9.05 9.0

Page 14: Chapter 6 Structures

Slide 14

Sort Structures (Cont.)struct request {

int number;double duration;

};

typedef struct request requesttype;

void input(requesttype request[], int *count);

Page 15: Chapter 6 Structures

Slide 15

Sort Structures (Cont.)

int main(void)

{

requesttype request[1000];

int count=0;…

input(request, &count);

sort_struct(request, count);

}

Page 16: Chapter 6 Structures

Slide 16

Sort Structures (Cont.)void input(requesttype request[], int *count){

int i;

for (i=0; scanf("%d", &request[i].number), request[i].number !=0;

i++){

scanf("%lf", &request[i]. duration);…

(*count)++;}

}

Page 17: Chapter 6 Structures

Slide 17

Sort Structures (Cont.)void sort_struct (requesttype w[], int n){

int i, j;for (i=0; i<n; ++i)

for (j=i+1; j<n;++j)if (w[i].duration > w[j].duration)

swap (&w[i], &w[j]);}

Page 18: Chapter 6 Structures

Slide 18

Sort Structures (Cont.)

void swap (requesttype *s, requesttype *t)

{

requesttype tmp;

tmp=*s;

*s=*t;

*t=tmp;

}

Page 19: Chapter 6 Structures

Slide 19

Sort Structures – Another Way (Cont.)void sort_struct (requesttype w[], int n){

int i, j;for (i=0; i<n; ++i)

for (j=i+1; j<n;++j)if (w[i].duration > w[j].duration){

swapInt (&w[i], &w[j]);swapDouble (&w[i], &w[j]);

}}

Page 20: Chapter 6 Structures

Slide 20

Sort Structures – Another Way (Cont.)

void swapInt (requesttype *s, requesttype *t)

{

int tmp;

tmp=s->number;

s->number=t->number;

t->number=tmp;

}

Page 21: Chapter 6 Structures

Slide 21

Sort Stuctures – Another Way (Cont.)

void swapDouble (requesttype *s, requesttype *t)

{

double tmp;

tmp=s->duration;

s->duration=t->duration;

t->duration=tmp;

}

Page 22: Chapter 6 Structures

Slide 22

Example

Helpful Code

Data

Sort Student Name and Grades Structure;

Program, Data

Page 23: Chapter 6 Structures

Slide 23

Operators Priority

Operator Same Priority Rule

(),postfix++/--,[],.,-> Left to right

Unary +/-, prefix++/--, !, ~,&, * Right to left

*, /, % Left to right

+, - Left to right

<<, >> Left to right

<, >, <=, >= Left to right

==, != Left to right

Page 24: Chapter 6 Structures

Slide 24

Operators Priority (Cont.)

Operator Same Priority Rule

&

^

|

&& Left to right

|| Left to right

?: Right to left

, Left to right

Page 25: Chapter 6 Structures

Slide 25

Union Create a new type (union union_name)

by union sets of different data types Declare as

union union_name {

type1 variable1;

…; };

Page 26: Chapter 6 Structures

Slide 26

Union (Cont.) Example:

union number { long i; float f;};

typedef union number number; number number1, number2; number1.i=100; number2.f=-1.23; printf(“%d%f\n”, number1.i, number1.f); printf(“%d%f\n”, number2.i, number2.f);

Page 27: Chapter 6 Structures

Slide 27

Example Helpful Code

Page 28: Chapter 6 Structures

Slide 28

Structure with Bit Fields Purpose: reduce space Declare structure data types using bits fields as

struct structure_name {unsigned field1: number of bits,

field2: number of bits, :0, // align to next word …; };

typedef struct structure_name structure_type;structure_type variable_list;

Page 29: Chapter 6 Structures

Slide 29

Structure with Bit Fields (Cont.) Example: Create a small_number that has 7 bits

of signed integer or floatstruct small_number {unsigned int_sign: 1, // 0: positive, 1: negative using 2s complement

i : 6, :0, // align to next word float_sign: 1, f : 6; // don’t worry align at the end};

typedef struct small_number small_number;small_number s_number1;

Page 30: Chapter 6 Structures

Slide 30

Structure with Bit Fields (Cont.) Example: (Cont.)

// assign 23 to snumber1

snumber1.int_sign=0;

snumber1.i=23;

Page 31: Chapter 6 Structures

Slide 31

Data Structure - stack Stack: insert (push) and delete (pop)

at the same place (top).

Page 32: Chapter 6 Structures

Slide 32

Example 1- stack Write a program that implements a stack of

characters using an array.

typedef struct stack {

char s[STACKSIZE];

int top;

} stack;

Page 33: Chapter 6 Structures

Slide 33

Example 1– stack (Cont.)void clear_stack (stack *stk) { stk->top=-1;};

void push(char c, stack *stk) { stk->top++; stk->s[stk->top]=c;}

Page 34: Chapter 6 Structures

Slide 34

Example 1– stack (Cont.)

char top (const stack *stk) {

return (stk->s[stk->top]);

};

char pop (stack *stk) {

return (stk->s[stk->top--]);

}

Page 35: Chapter 6 Structures

Slide 35

Example 1– stack (Cont.)

int is_full (const stack *stk) {

return ((int) (stk->top == STACKSIZE-1));

};

int is_empty (const stack *stk) {

return ((int) (stk->top == -1));

};

Page 36: Chapter 6 Structures

Slide 36

Example 2- stack Write a program that implements a stack of

integers using a linked list.typedef struct node {

int info;struct node *next;

} node;

typedef struct stack {node * head;

} stack;;

Page 37: Chapter 6 Structures

Slide 37

Example 2– stack (Cont.)

void clear_stack(stack *stk)

{

stk->head=NULL;

}

Page 38: Chapter 6 Structures

Slide 38

Example 2– stack (Cont.)// insert item to head, delete from headvoid push (int item, stack *stk) {

node *newnode;

newnode = malloc(sizeof(node)); // dynamically create a new nodeif (!newnode)

printf("No memory is available.\n");else{

newnode->info= item;newnode->next= stk->head;

stk->head=newnode;} // else

}

Page 39: Chapter 6 Structures

Slide 39

Example 2– stack (Cont.)

int top (const stack *stk)

{

return (stk->head->info);

}

Page 40: Chapter 6 Structures

Slide 40

Example 2– stack (Cont.)int pop (stack *stk){

int item;node *deletednode;

deletednode=stk->head;item=deletednode->info;stk->head=deletednode->next;free(deletednode);

return item;}

Page 41: Chapter 6 Structures

Slide 41

Example 2– stack (Cont.)

int isempty (stack *stk)

{

return (stk->head == NULL);

}

Page 42: Chapter 6 Structures

Slide 42

Example 2– stack (Cont.)void output (stack stk){

printf ("--------------------------”);Printf(“All items in the stack:-------------------------\n");for (;!isempty(&stk);) {

printf("%d\n", top(&stk));stk.head=(stk.head)->next;

}}

Page 43: Chapter 6 Structures

Slide 43

Example 2– stack (Cont.)

Helpful Code

Data

Page 44: Chapter 6 Structures

Slide 44

Data Structure - Queue Insert (enqueue) at the tail and

Delete (dequeue) at the head.

Page 45: Chapter 6 Structures

Slide 45

Example - Queue Write a program that implements a queue of

integers using a linked list.struct node {

int info;struct node *next;

};typedef struct node node;node *head=NULL, *tail=NULL; // initialize

Page 46: Chapter 6 Structures

Slide 46

Example – Queue (Cont.)

int isempty (node * head)

{

return (head == NULL);

}

Page 47: Chapter 6 Structures

Slide 47

Example – Queue (Cont.)// insert item to tail, delete from headvoid enqueue (node **ptrhead,

node **ptrtail, int item){

node *newnode;

// dynamically create a new nodenewnode = malloc(sizeof(node)); if (!newnode)

printf("No memory is available.\n");

Page 48: Chapter 6 Structures

Slide 48

Example – Queue (Cont.)// insert item to tail, delete from head (Cont.)else{

newnode->info= item;newnode->next=NULL;

if (isempty(*ptrhead)) // if (!(*ptrhead)) means head is equal to NULL*ptrhead=newnode;

else(*ptrtail)->next=newnode;

*ptrtail=newnode;} // else

} // enqueue

Page 49: Chapter 6 Structures

Slide 49

Example – Queue (Cont.)// delete from head and return infoint dequeue (node **ptrhead, node **ptrtail){

int item;node *deletednode;

deletednode=*ptrhead;item=deletednode->info;*ptrhead=deletednode->next;if (isempty(*ptrhead))

*ptrtail=NULL;free(deletednode);

return item;}

Page 50: Chapter 6 Structures

Slide 50

Example – Queue (Cont.)void output (node *head){

printf ("--------------------------”); printf(“All items in the queue:-------------------------\

n");for (;!isempty(head);) // for (;head != NULL;) {

printf("%d\n", head->info);head=head->next;

}}

Page 51: Chapter 6 Structures

Slide 51

Example – Queue (Cont.)

Program (node is int) Code

Data

Program (node is a structure) Code

Data

Page 52: Chapter 6 Structures

Slide 52

Data Structure – Binary Tree Each (parent) node has at most 2 children Binary search tree:

right child node value > parent node value > left

child value

Page 53: Chapter 6 Structures

Slide 53

Example – Binary search tree Write a program that implements a

binary search tree of integers using a linked list.

typedef struct node {

struct node *left;

int info;

struct node *right;

} node;

Page 54: Chapter 6 Structures

Slide 54

Example – Binary search tree (Cont.)

typedef struct tree {

node * root;

} tree;

Page 55: Chapter 6 Structures

Slide 55

Example – Binary search tree (Cont.)

void clear_tree(tree *bst)

{

bst->root=NULL;

}

Page 56: Chapter 6 Structures

Slide 56

Example – Binary search tree (Cont.)void insert (int item, tree *bst) {

node *newnode;

if (bst->root == NULL) // base case{

newnode = malloc(sizeof(node)); // dynamically create a new nodeif (newnode == NULL)

printf("No memory is available.\n");else{

newnode->info= item;newnode->left= NULL;newnode->right= NULL;bst->root=newnode;printf("%d\n", bst->root->info);

}}

Page 57: Chapter 6 Structures

Slide 57

Example – Binary search tree (Cont.)

Else // inductive case{

if (item> bst->root->info)bst->root=bst->root->right;

elsebst->root=bst->root->left;

insert(item, bst);}} // insert

Page 58: Chapter 6 Structures

Slide 58

Example – Binary search tree (Cont.)

Helpful Code

Data

Page 59: Chapter 6 Structures

Slide 59

PracticeGiven struct student {

char lastname[15]; long studentid; char grade;

}; struct student tmp, *p=&tmp; tmp.grade='A'; tmp.lastname="Casanova"; tmp.studentid=910017;

Page 60: Chapter 6 Structures

Slide 60

Practice (Cont.)Find the values of the following table: Expression Value ________ _____ tmp.grade tmp.lastname (*p).studentid *p->lastname+1 *(p->lastname+2)

Page 61: Chapter 6 Structures

Slide 61

Practice (Cont.)Find the values of the following table: Expression Value ________ _____ tmp.grade ‘A’tmp.lastname “Casanova”(*p).studentid 910017*p->lastname+1 ‘D’*(p->lastname+2) ‘s’

Page 62: Chapter 6 Structures

Slide 62

References Deitel & Deitel: C How to Program, 4th ed.,

Chapter 10 & 12, Prentice Hall