chapter 5

34
CHAPTER 5 STRUCTURE 1

Upload: elijah

Post on 13-Feb-2016

63 views

Category:

Documents


0 download

DESCRIPTION

CHAPTER 5. STRUCTURE. User Defined Data Types. Objectives: In this chapter you will learn about, Introduction Declaring Structure Type & Structure Variables Referring and initializing structure elements Passing structures to a function Using typedef Example using structure - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CHAPTER 5

CHAPTER 5STRUCTURE

1

Page 2: CHAPTER 5

Objectives: In this chapter you will learn about, Introduction Declaring Structure Type & Structure Variables Referring and initializing structure elements Passing structures to a function Using typedef Example using structure Enumeration constants

2

User Defined Data Types

Page 3: CHAPTER 5

So far we have only used data types which have been defined by C such as int, double and char.

It is also possible to create our own data types. A user defined data type is called a structure. A structure can contain both built-in data types

and another structure. The concept of structure is pretty much the

same as arrays except that in an array, all the data is of the same types but in a structure, the data can be of different types.

3

Introduction

Page 4: CHAPTER 5

General syntax:struct structure_name {

data_type element1;data_type element2;. . .

}; Example:

struct student {char name[20];int studentID;char major[50];

};

4

Declaring Structure TypeAlso called as structure tag

Components / members

Page 5: CHAPTER 5

After declaring a structure type, we may declare variables that are of that type. A structure variable declaration requires:◦ The keyword struct◦ The structure type name◦ A list of members (variable names) separated by

commas◦ A concluding semicolon

Then, assume that variable of structure type student is my_student. So the declaration should be written as;

struct student my_student;

5

Declaring Structure Variables

Page 6: CHAPTER 5

By including this declaration in our program, we are informing the compiler about a new data type which is a user defined data type.

The declaration just makes the compiler aware of existent of new data type but does not take an action yet.

Based on the declaration ofstruct student my_student;

causes the compiler to reserve memory space for variable my_student and the components of its structure.

6

Based on example: struct student

Page 7: CHAPTER 5

7

Based on example: struct student cont…

Structure variable Components Values

name

majorstudentID

Simon0078CS

my_student

Conceptual memory structure variable my_student of type student

Page 8: CHAPTER 5

It is possible to combine the declarations of a structure type and a structure variable by including the name of the variable at the end of the structure type declaration.

8

Based on example: struct student cont…

struct student {char name[20];

int studentID;char major[50];

}; struct student my_student;

struct student {char name[20];

int studentID;char major[50];

} my_student;

=

Page 9: CHAPTER 5

Members of a structure declaration can be of any type, including another structure variable.

Suppose we have the following structure declaration which this struct will be as a member of struct type student:

struct address { int no; char street[20]; int zipcode;

}addr;

9

Declaring Nested Structure

Page 10: CHAPTER 5

We can rewrite the structure student declaration as follow:

This structure type student can be written as;

10

Declaring Nested Structure cont…

struct student {char name[20];int studentID;char major[50];struct address addr;

} my_student;

Page 11: CHAPTER 5

struct student {char name[20];int studentID;char major[50];struct address{ int no; char street[20]; int zipcode;}addr;

} my_student;

11

Declaring Nested Structure cont…

Page 12: CHAPTER 5

A structure contains many elements. Each members of a structure can be referred to / accessed by using the operator “.” (dot)

Let us use the structure student which we have seen before as an example:

12

Referring and Initializing Structure Members

struct student {char name[20];

int studentID;char major[50];

} my_student;

Page 13: CHAPTER 5

There for to refer to the element of a structure, we may write as follow;

my_student.name;my_student.studentID;my_student.major;

Therefore, we can initialize each elements of a structure individually such as:

struct student my_student;my_student.studentID = 10179;

13

Referring and Initializing Structure Members

Page 14: CHAPTER 5

Or we can initialize the structure while we are creating an instance of the structure:struct student my_student = {“Ahmad”, 10179, “IT”}

Notice that it is possible to use the ‘=’ operator on a struct variable. When the ‘=’ sign is used, each elements of the structure at the right hand side is copied into the structure at the left hand side.

14

Referring and Initializing Structure Members

Page 15: CHAPTER 5

struct birthdate {int month;int day;int year;

}Picasso;struct birthdate Picasso = {10, 25, 1881};printf(“Picasso was born : %d/%d/%d\n”, Picasso.day,

Picasso.month, Picasso.year);

Output :Picasso was born : 25/10/1881

15

Example 1

Page 16: CHAPTER 5

We can pass the student structure that we have created before to a function called Read( ) as follows:

void Read (struct student s1); In the function above, a copy of the student

structure will be created locally for the use of the function. But any changes to the structure inside the function will not affect the actual structure.

It is also possible to use pointers and pass the reference of the structure to the function. This way, any changes inside the function will change the actual structure as well.

17

Passing Structures to a Function

Page 17: CHAPTER 5

To pass a reference, the Read( ) function can be written this way:void Read(struct student *s1);

Take note that when a structure is declared as a pointer, the elements in the structure cannot be referred to using the ‘.’ operator anymore. Instead, they need to be accessed using the ‘->’ operator.

For example:void Read(struct student *s1) {s1->studentID = 10179;scanf(“%s”, &(s1->name));scanf(“%s”, &(s1->major));}

18

Passing Structures to a Function

Page 18: CHAPTER 5

#include <stdio.h>struct car {

char maker[20];char model[20];int year;

};void input(struct car *sp);void output(struct car *sp);

void main(){struct car firstcar;input (&firstcar);output(&firstcar);printf("End of my act!\n");

}

19

Example 3

Page 19: CHAPTER 5

void input(struct car *sp){printf("What is the maker of your car? ");scanf("%s", &sp->maker);printf("What is the model of your car? ");scanf("%s", &sp->model);printf("What year is your car? ");scanf("%d", &sp->year);

}

void output(struct car *sp){printf("Your car is : %s, %s, %d\n", sp->maker, sp->model, sp->year);printf("Nice car\n");

}

20

Cont…

Page 20: CHAPTER 5

/* Sample outputWhat is the maker of your car? HondaWhat is the model of your car? IntegraWhat year is your car? 2004Your car is : Honda, Integra, 2004Nice carEnd of my act!Press any key to continue*/

21

Cont…

Page 21: CHAPTER 5

The keyword typedef provides a mechanism for creating synonyms (aliases) for previously defined data types.

Typedefs give a way to provide consistent type names◦ Let user-defined types declare associated types◦ Let you create type names for other purposes, convenience

Here is an example on how to use typedef when declaring a structure:

typedef struct student { char name[20];int studentID;char major[50];struct address addr;

} StudentData;

22

Using typedef in Structure Declarations

Page 22: CHAPTER 5

By using typedef, we now do not have to write the word “struct” before declaring a struct variable. Instead of writing:

struct student my_student;we can now write:

StudentData my_student; Same thing with passing the structure to a

function:void Read(StudentData *s1);

23

Using typedef in Structure Declarations

Page 23: CHAPTER 5

24

Example Using typedef#include <stdio.h>#define NUM_STUDENTS 10typedef struct pelajar {

int studentID;char name[20];int score;char grade;

}StudentData;void Read (StudentData student[]);void CountGrade (StudentData student[]);

void main ( ) {

StudentData student[NUM_STUDENTS];Read(student);CountGrade(student);

}

Page 24: CHAPTER 5

25

void Read (StudentData student[]) {

int i;for (i = 0; i < NUM_STUDENTS; i++) {

printf("Enter the studentID: ");scanf("%d", &student[i].studentID);printf("Enter the name: ");scanf("%s", &student[i].name);printf("Enter the score: ");scanf("%d", &student[i].score);printf("\n");

}}

Example Using typedef

Page 25: CHAPTER 5

26

void CountGrade (StudentData student[]) {

int i;for (i = 0; i < NUM_STUDENTS; i++) { if (student[i].score > 90) student[i].grade = 'A'; else if (student[i].score > 80)

student[i].grade = 'B'; else if (student[i].score > 65)

student[i].grade = 'C'; else if (student[i].score > 50)

student[i].grade = 'D'; else

student[i].grade = 'F';printf("The grade for %s is %c\n", student[i].name, student[i].grade);printf("\n");}

}

Example Using typedef

Page 26: CHAPTER 5

27

/* Sample OutputEnter the studentID: 789654Enter the name: SimaonEnter the score: 88

Enter the studentID: 741258Enter the name: JackEnter the score: 79:::The grade for Simaon is B

The grade for Jack is C::Press any key to continue*/

Example Using typedef

Page 27: CHAPTER 5

28

How to Parse and Define C TypesAt this point we have seen a few basic types, arrays, pointer types, and structures. So far we’ve glossed over how types are named.

int x; /* int; */ typedef int T; int *x; /* pointer to int; */ typedef int *T; int x[10]; /* array of ints; */ typedef int T[10]; int *x[10]; /* array of pointers to int; */ typedef int *T[10]; int (*x)[10]; /* pointer to array of ints; */ typedef int (*T)[10];

C type names are parsed by starting at the type name and working outwards according to the rules of precedence:

int (*x)[10]; x isa pointer toan array ofint

int *x[10];

x is an array ofpointers toint Arrays are the primary source

of confusion. When in doubt, use extra parens to clarify the expression.

typedef defines a new type

Page 28: CHAPTER 5

An enumeration, introduced by the keyword enum, is a set of integer constants represented by identifiers. (to specify one after another)

Example:enum islamic_months {

muharam, safar, rabiulawal, rabiulakhir, jamadilawal, jamadilakhir, rejab, syaaban, ramadhan, syawal, zulkaedah, zulhijjah

}; Each of the identifiers actually has a value,

starting with 0 (unless specified otherwise). Therefore, we can treat them as integers.

29

Enumeration Constants

Page 29: CHAPTER 5

If we want the enumeration to start with a value other than 0, we can assign the value to the first identifier:enum islamic_months {

muharam = 1, safar, rabiulawal, rabiulakhir,

jamadilawal, jamadilakhir, rejab, syaaban, ramadhan, syawal, zulkaedah, zulhijjah

}; Same as with the other data types, before an

enum can be used, a variable needs to be declared:

enum islamic_months months;30

Enumeration Constants

Page 30: CHAPTER 5

There are cases where it is appropriate for us to use an enum. This is an example of such a case:

enum islamic_months months;GetMonth (&months);switch (months) {

case muharam:. . .

break;case safar:

. . .break;. . .

}

31

Enumeration Constants

Page 31: CHAPTER 5

This is another case where it is appropriate to use an enum:

enum Boolean {FALSE, TRUE};void main ( ) {

int list[];Boolean found;

Read(list);found = Search(list);if (found == TRUE)

printf(“FOUND!!”);else

printf(“Cannot find the requested item”);

}

32

Enumeration Constants

Page 32: CHAPTER 5

33

#include <stdio.h>

enum months {JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};

void main ( ) {enum months month;char *monthsName[] = {“January”, “February”,

“March”, “April”, “May”, “June”, “July”, “August”,

“September”, “October”, “November”, “December”};

for (month = JAN; month <= DEC; month++)printf(“%d %s\n”, month,

monthName[month-1]);}

Enumeration Constants

Page 33: CHAPTER 5

34

Output: 1 January2 February3 March4 April5 May6 June7 July8 August9 September10 October11 November12 December

Enumeration Constants

Page 34: CHAPTER 5

This chapter you learned about structures◦ Structure type and variable declarations◦ How structure members can be accessed◦ How they can be initialized

You learned that structures can be passed between function

Introduced you to another user defined data type which is enumeration

T.H.E E.N.D

35

SUMMARY