1 / 34

CHAPTER 5

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

elijah
Download Presentation

CHAPTER 5

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CHAPTER 5 STRUCTURE

  2. 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 • Enumeration constants

  3. Introduction • 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.

  4. Also called as structure tag Components / members Declaring Structure Type • General syntax: struct structure_name { data_type element1; data_type element2; . . . }; • Example: struct student { char name[20]; int studentID; char major[50]; };

  5. Declaring Structure Variables • 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;

  6. Based on example: struct student • 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 of struct student my_student; causes the compiler to reserve memory space for variable my_student and the components of its structure.

  7. Structure variable Components Values name Simon my_student studentID 0078 major CS Based on example: struct student cont… Conceptual memory structure variable my_studentof type student

  8. Based on example: struct student cont… • 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. • structstudent { • char name[20]; • intstudentID; • char major[50]; • }; • struct student my_student; • structstudent { • char name[20]; • intstudentID; • char major[50]; • } my_student; =

  9. Declaring Nested Structure • 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;

  10. Declaring Nested Structure cont… • We can rewrite the structure student declaration as follow: • This structure type student can be written as; struct student { char name[20]; intstudentID; char major[50]; struct address addr; } my_student;

  11. Declaring Nested Structure cont… struct student { char name[20]; int studentID; char major[50]; struct address{ int no; char street[20]; int zipcode; }addr; } my_student;

  12. Referring and Initializing Structure Members • 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: • struct student { • char name[20]; • int studentID; • char major[50]; • } my_student;

  13. Referring and Initializing Structure Members • 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;

  14. Referring and Initializing Structure Members • 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.

  15. Example 1 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

  16. Passing Structures to a Function • 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 • 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. Example 3 #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. Cont… 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… /* Sample output What is the maker of your car? Honda What is the model of your car? Integra What year is your car? 2004 Your car is : Honda, Integra, 2004 Nice car End of my act! Press any key to continue */

  21. Using typedef in Structure Declarations • 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: typedefstruct student { char name[20]; intstudentID; char major[50]; struct address addr; } StudentData;

  22. Using typedef in Structure Declarations • 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: StudentDatamy_student; • Same thing with passing the structure to a function: void Read(StudentData *s1);

  23. ExampleUsing typedef #include <stdio.h> #define NUM_STUDENTS 10 typedefstructpelajar { intstudentID; 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); }

  24. Example Using typedef void Read (StudentData student[]) { inti; 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"); } }

  25. Example Using typedef void CountGrade (StudentData student[]) { inti; 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"); } }

  26. Example Using typedef /* Sample Output Enter the studentID: 789654 Enter the name: Simaon Enter the score: 88 Enter the studentID: 741258 Enter the name: Jack Enter the score: 79 : : : The grade for Simaon is B The grade for Jack is C : : Press any key to continue */

  27. x is an array of pointers to int int *x[10]; int (*x)[10]; x is a pointer to an array of int How to Parse and Define C Types At 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]; typedef defines a new type C type names are parsed by starting at the type name and working outwards according to the rules of precedence: Arrays are the primary source of confusion. When in doubt, use extra parens to clarify the expression.

  28. Enumeration Constants • An enumeration, introduced by the keyword enum, is a set of integer constants represented by identifiers. (to specify one after another) • Example: enumislamic_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 • 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 • 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 • 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 #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]); }

  33. Enumeration Constants • Output: • 1 January • 2 February • 3 March • April • May • June • July • August • September • October • November • December

  34. SUMMARY • 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

More Related