chapter 9-structures

20
CHAPTER 9 1 DAE 20102 COMPUTER PROGRAMMING CHAPTER 9 STRUCTURES

Upload: jay-leong

Post on 20-Jan-2015

60 views

Category:

Education


0 download

DESCRIPTION

CHAPTER 9, COMPUTER PROGRAMMING (DAE 20102)

TRANSCRIPT

Page 1: Chapter 9-Structures

CHAPTER 9 1

DAE 20102COMPUTER PROGRAMMING

CHAPTER 9

STRUCTURES

Page 2: Chapter 9-Structures

CHAPTER 9 2

INTRODUCTIONStructures are C’s way of grouping collections of data into a single manageable unit.– This is also the fundamental element of C upon which

most of C++ is built (i.e., classes).– Similar to Java's classes.

A structure in C is a collection of items of different types. Structures, or structs, are very useful in creating data structures larger and more complex.What the differences between array and structs?Array=same related data items of the same type into a single entityStructs=allows different data types to be grouped together and to be treated as a single entity

Page 3: Chapter 9-Structures

CHAPTER 9 3

DECLARING STRUCTURES

A structure=derived data type that represents a collection of related data items called components that are not necessarily of the same data typestruct is reserved word indicating the beginning structure definitionStructure tag is the name of the structure type used to declare structure variables. Structure tag is optional

Page 4: Chapter 9-Structures

CHAPTER 9 4

DECLARING STRUCTURESstructure definition: general format: struct tag_name { data type member1; data type member2; … … }

Structure declaring format

Page 5: Chapter 9-Structures

CHAPTER 9 5

DECLARING STRUCTURESDefine struct variables:

struct coord { int x,y ;} first, second;

Another Approach: struct coord {

int x,y ;};

............... struct coord first, second; /* declare variables */ struct coord third;

Structure declaring format-

another approach

Page 6: Chapter 9-Structures

CHAPTER 9 6

DECLARING STRUCTURES

Example: struct lib_books { char title[20]; char author[15]; int pages; float price; };

struct lib_books, book1, book2, book3;

• Keyword struct declares a structure to holds the details of four fields namely title, author pages and price. • These are members of the structures. Each member may belong to different or same data type. • Declares book1,book2,book3 as variables of type struct lib_books each declaration has four elements of the structure lib_books.

Page 7: Chapter 9-Structures

CHAPTER 9 7

DECLARING STRUCTURES

You can even use a typedef if your don't like having to use the word “struct”

typedef struct coord coordinate;coordinate first, second;

In some compilers, and all C++ compilers, you can usually simply say just:

coord first, second;

Page 8: Chapter 9-Structures

CHAPTER 9 8

Assigning values to membersThere are three ways of assigning values to the members in the structure

1st method

We can use scanf statement to assign values like

scanf(“%s”,&book1.file); scanf(“%d”,& book1.pages);

Page 9: Chapter 9-Structures

CHAPTER 9 9

Assigning values to members2nd method

Or we can assign variables to the members of book1 The members themselves are not variables they should be linked to structure variables in order to make them meaningful members. The link between a member and a variable is established using the member operator ‘.’ Which is known as dot operator or period operator.

strcpy(book1.title,”basic”); strcpy(book1.author,”Balagurusamy”); book1.pages=250; book1.price=28.50;

Page 10: Chapter 9-Structures

CHAPTER 9 10

Assigning values to members

3rd method

Static struct

Directly assign values to the variable

book2={“Programming c”,”Deitel”,230,18.90}

Page 11: Chapter 9-Structures

CHAPTER 9 11

Example 1/* Example program for using a structure*/ #include< stdio.h > int main (void) {

struct { int id_no; char name[20]; char address[20]; char combination[3]; int age;

} newstudent;

printf(“Enter the student information”); printf(“Now Enter the student id_no”); scanf(“%d”,&newstudent.id_no);

printf(“Enter the name of the student”); scanf(“%s”,&newstudent.name); printf(“Enter the address of the student”); scanf(“%s”,&newstudent.address);

printf(“Enter the cmbination of the student”); scanf(“%d”,&newstudent.combination);

printf(“Enter the age of the student”); scanf(“%d”,&newstudent.age);

printf(“Student information\n”); printf(“student id_number=%d\n”,newstudent.id_no); printf(“student name=%s\n”,newstudent.name); printf(“student Address=%s\n”,newstudent.address); printf(“students combination=%s\n”,newstudent.combination); printf(“Age of student=%d\n”,newstudent.age);

}

Page 12: Chapter 9-Structures

CHAPTER 9 12

Structure AssignmentA structure can be assigned to another variable of the same structure type using a simple assignment statement.

This assign a struct to another

{

struct part a,b;

b.price = 39.99;

b.name = "floppy";

a = b;

}

Page 13: Chapter 9-Structures

CHAPTER 9 13

Nested structureA structure may be defined as a member of another structure. In nested structures, the declaration of the embedded structure must appear before the declarations of other structures. struct date { int day; int month; int year; }; struct student { int id_no; char name[20]; char address[20]; char combination[3]; int age; structure date def; structure date doa; }oldstudent, newstudent;

Student structure

Date structure

Page 14: Chapter 9-Structures

CHAPTER 9 14

Example 2#include <stdio.h>

struct coord {

int x;

int y;

};

struct rectangle {

struct coord topleft;

struct coord bottomrt;

};

int main () {int length, width;long area;struct rectangle mybox;mybox.topleft.x = 0;mybox.topleft.y = 0;mybox.bottomrt.x = 100;mybox.bottomrt.y = 50;width = mybox.bottomrt.x –

mybox.topleft.x;length = mybox.bottomrt.y –

mybox.topleft.y;area = width * length;printf ("The area is %ld units.\n", area);

}

Page 15: Chapter 9-Structures

CHAPTER 9 15

Structures And PointersA pointer to a structure identifies its address in the memory. Example

struct date{ Me ={23,5,1974};*pointer_to_Me;

};

2 types of assigning value using pointer– (.) dot operator– (->) arrow operator

Direct Access (dot)

Notation

Arrow Notation

Pointer Notation

Member Value

Me.day Me ->day (*Ptr).day 23

Me.month Me ->month (*Ptr).month 5

Me.year Me ->year (*Ptr).year 1974

Page 16: Chapter 9-Structures

CHAPTER 9 16

Functions and structures We can pass structures as arguments to functions.

Unlike array names however, which always point to the start of the array, structure names are not pointers.

A structure may be passed into a function as individual member or a separate variable.

As a result, when we change structure parameter inside a function, we don’t effect its corresponding argument.

Page 17: Chapter 9-Structures

CHAPTER 9 17

Example 3struct book {

float price;

char abstract[5000];

};

void print_abstract( struct book *p_book)

{

puts( p_book->abstract );

};

struct pairInt {int min, max;

};struct pairInt min_max(int x,int y){

struct pairInt pair;pair.min = (x > y) ? y : x;pair.max = (x > y) ? x : y;return pairInt;

}int main(){

struct pairInt result;result = min_max( 3, 5 );printf("%d<=%d", result.min, result.max);

}

Page 18: Chapter 9-Structures

CHAPTER 9 18

Arrays of structure It is possible to define an array of structures for example if we are maintaining information of all the students in the college and if 100 students are studying in the college.

We need to use an array than single variables

An array of structures can be assigned initial values just as any other array can.

Page 19: Chapter 9-Structures

CHAPTER 9 19

Structures Containing ArraysArrays within structures are the same as any other member element.

For example:

struct record { float x;

char y [5] ;} ;

Logical organization:

float char[5]

record

Page 20: Chapter 9-Structures

CHAPTER 9 20

#include <stdio.h>

struct entry {

char fname [20];

char lname [20];

char phone [10];

} ;

int main() {

struct entry list[4];

int i;

for (i=0; i < 4; i++) {

printf ("\nEnter first name: ");

scanf ("%s", list[i].fname);

printf ("Enter last name: ");

scanf ("%s", list[i].lname);

printf ("Enter phone in 123-4567 format: ");

scanf ("%s", list[i].phone);

}

printf ("\n\n");

for (i=0; i < 4; i++) {

printf ("Name: %s %s", list[i].fname, list[i].lname);

printf ("\t\tPhone: %s\n", list[i].phone);

}

}

Example 4