TypesObjectives: In this chapter you will learn about, Introduction Declaring Structure Type & Structure Variables Referri...
IntroductionSo far we have only used data types which havebeen defined by C such as int, double and char.It is also possib...
DefinitionA structure is a derived data type thatrepresents a collection of a related dataitems called components (or memb...
Declaring Structure TypeGeneral syntax:              Also called as structure tag   struct structure_name {           data...
Declaring Structure VariablesAfter declaring a structure type, we maydeclare variables that are of that type. Astructure v...
Based on example: struct student By including this declaration in our program, we are informing the compiler about a new d...
Structure variable   Components      Values                      name           Simon  my_student          studentID      ...
It is possible to combine the  declarations of a structure type and a  structure variable by including the name  of the va...
Declaring Nested StructureMembers of a structure declaration canbe of any type, including anotherstructure variable.Suppos...
We can rewrite the structure studentdeclaration as follow:struct student {        char name[20];        int studentID;    ...
struct student {        char name[20];        int studentID;        char major[50];        struct address{            int ...
Referring and Initializing Structure ElementsA structure contains many elements. Each elements of astructure can be referr...
Therefore, we can initialize each elements ofa structure individually such as:   struct student my_student;   my_student.s...
Examplestruct birthdate {     int month;     int day;     int year;};struct birthdate Picasso = {10, 25, 1881};printf(“Pic...
Passing Structures to a FunctionCall by Value:  We can pass the student structure that we have  created before to a functi...
Example Using Structure: Call by value#include <stdio.h>#include <string.h>struct student{          char name[20];        ...
Example Using Structure: A Function that return a structure#include <stdio.h>#include <string.h>struct student{          c...
Call by referenceIt is also possible to use pointers and pass the referenceof the structure to the function. This way, any...
Take note that when a structure is declared as apointer, the elements in the structure cannot bereferred to using the ‘.’ ...
Example Using Structure: Call by reference#include <stdio.h>#include <string.h>struct student{          char name[20];    ...
Using typedef in Structure DeclarationsThe keyword typedef provides amechanism for creating synonyms(aliases) for previous...
By using typedef:    typedef struct student StudentData; we are now aliasing the structure with aname to be used throughou...
Example : using typedef#include <stdio.h>#include <string.h>struct student{    char name[20];    int id;};typedef struct s...
Example: Array of structure#include <stdio.h>#define NUM_STUDENTS 10struct student {         int studentID;         char n...
void Read (StudentData student[]){       int i;       for (i = 0; i < NUM_STUDENTS; i++) {                 printf("Enter t...
void CountGrade (StudentData student[]){         int i;         for (i = 0; i < NUM_STUDENTS; i++) {            if (studen...
/* Sample OutputEnter the studentID: 789654Enter the name: SalmanEnter the score: 96Enter the studentID: 741258Enter the n...
Example#include <stdio.h>struct car{        char maker[20];        char model[20];        int year;};void input(struct car...
void input(struct car *sp){printf("What is the maker of your car? ");gets(sp->maker);printf("What is the model of your car...
/* Sample outputWhat is the maker of your car? HondaWhat is the model of your car? StreamWhat year is your car? 2003Your c...
Enumeration ConstantsAn enumeration, introduced by the keywordenum, is a set of integer constants representedby identifier...
If we want the enumeration to start with avalue other than 0, we can assign the value tothe first identifier:enum islamic_...
There are cases where it is appropriate for usto use an enum. This is an example of such acase:   enum islamic_months mont...
This is another case where it is appropriate touse an enum:   enum Boolean {FALSE, TRUE};   void main ( ) {          int l...
#include <stdio.h>enum months {JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG,SEP, OCT, NOV, DEC};void main ( ) {       enum m...
Output:1   January2   February3   March4   April5   May6   June7   July8   August9   September10 October11 November12 Dece...
SUMMARYIn this chapter you have learnt about  Structure type and variable declarations  How structure members can be acces...
Upcoming SlideShare
Loading in...5
×

Structure In C++

1,227

Published on

0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,227
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
131
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Structure In C++

  1. 1. TypesObjectives: 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 User Defined Data Types - updated NI@2006 1
  2. 2. IntroductionSo far we have only used data types which havebeen 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 typesand another structure.The concept of structure is pretty much thesame as arrays except that in an array, all thedata is of the same types but in a structure, thedata can be of different types. User Defined Data Types - updated NI@2006 2
  3. 3. DefinitionA structure is a derived data type thatrepresents a collection of a related dataitems called components (or members)that are not necessarily of the same datatype. User Defined Data Types - updated NI@2006 3
  4. 4. Declaring Structure TypeGeneral syntax: Also called as structure tag struct structure_name { data_type element1; data_type element2; Components / members . . . };Example: struct student { char name[20]; int studentID; char major[50]; }; User Defined Data Types - updated NI@2006 4
  5. 5. Declaring Structure VariablesAfter declaring a structure type, we maydeclare variables that are of that type. Astructure variable declaration requires: The keyword struct The structure type name A list of members (variable names) separated by commas A concluding semicolonThen, assume that variable of structure typestudent is my_student. So the declarationshould be written as; struct student my_student; User Defined Data Types - updated NI@2006 5
  6. 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 the 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. User Defined Data Types - updated NI@2006 6
  7. 7. Structure variable Components Values name Simon my_student studentID 0078 major CSConceptual memory structure variable my_student of typestudent (assuming that the components of variablemy_student have already been assigned values) User Defined Data Types - updated NI@2006 7
  8. 8. 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.struct student { struct student { char name[20]; char name[20]; int studentID; int studentID; char major[50]; = char major[50];}; } my_student;struct student my_student; User Defined Data Types - updated NI@2006 8
  9. 9. Declaring Nested StructureMembers of a structure declaration canbe of any type, including anotherstructure variable.Suppose we have the followingstructure declaration, which is amember of struct type student: struct address { int no; char street[20]; int zipcode; }; User Defined Data Types - updated NI@2006 9
  10. 10. We can rewrite the structure studentdeclaration as follow:struct student { char name[20]; int studentID; char major[50]; struct address addr;};This structure type student can bewritten as; User Defined Data Types - updated NI@2006 10
  11. 11. struct student { char name[20]; int studentID; char major[50]; struct address{ int no; char street[20]; int zipcode; };}; User Defined Data Types - updated NI@2006 11
  12. 12. Referring and Initializing Structure ElementsA structure contains many elements. Each elements of astructure can be referred to / accessed by using thecomponent selection operator “.” (dot).Let us use the structure student which we have seen before asan example: struct student { char name[20]; int studentID; char major[50]; }; struct student my_student;Therefore to refer to the element of a structure, we may write asfollow; my_student.name; my_student.studentID; my_student.major; User Defined Data Types - updated NI@2006 12
  13. 13. Therefore, we can initialize each elements ofa structure individually such as: struct student my_student; my_student.studentID = 10179;Or we can initialize the structure while we arecreating 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 structureat the right hand side is copied into thestructure at the left hand side. User Defined Data Types - updated NI@2006 13
  14. 14. Examplestruct birthdate { int month; int day; int year;};struct birthdate Picasso = {10, 25, 1881};printf(“Picasso was born : %d/%d/%dn”, Picasso.day, Picasso.month, Picasso.year);Output : Picasso was born : 25/10/1881 User Defined Data Types - updated NI@2006 14
  15. 15. Passing Structures to a FunctionCall by Value: We can pass the student structure that we have created before to a function called display( ) as follows: void display (struct student); /* function prototype */ display (student1); /* function call */ void display (struct student s1); /* function header */ where student1 is a variable of type struct student. In the above function, a copy of the student structure will be created locally for the use of the function. Any changes to the structure inside the function will not affect the actual structure. User Defined Data Types - updated NI@2006 15
  16. 16. Example Using Structure: Call by value#include <stdio.h>#include <string.h>struct student{ char name[20]; int id;};void display(struct student); /* function prototype */void main(void){ struct student student1; strcpy(student1.name, "Ahmad"); /*initialising variable */ student1.id = 12345; /*initialising variable */ display(student1);}void display(struct student s1) /* make a local copy of the structure */{ printf("Name: %sn", s1.name); printf("ID: %dn", s1.id);} User Defined Data Types - updated NI@2006 16
  17. 17. Example Using Structure: A Function that return a structure#include <stdio.h>#include <string.h>struct student{ char name[20]; int id;};struct student read(void); /* function prototype */void main(void){ struct student student1; student1 = read(); /*function call */ printf("Name: %s", student1.name); printf("nID: %dn", student1.id);}struct student read(void){ struct student s1; printf("Enter name:"); scanf("%s",s1.name); /* alternative: gets(s1.name) ; */ printf("Enter ID:"); scanf("%d",&s1.id); return s1;} User Defined Data Types - updated NI@2006 17
  18. 18. Call by referenceIt is also possible to use pointers and pass the referenceof the structure to the function. This way, any changesinside the function will change the actual structure as well.To pass a structure variable as a reference, the Read( )function can be written this way: void Read(struct student *); /* function prototype */ Read(&student1); /* function call */ void Read(struct student *s1); /* function header */where student1 is a variable of type struct student. User Defined Data Types - updated NI@2006 18
  19. 19. Take note that when a structure is declared as apointer, the elements in the structure cannot bereferred to using the ‘.’ operator anymore. Instead,they need to be accessed using the ‘->’ operator(indirect component selection operator ).For example: void Read(struct student *s1) { s1->studentID = 10179; scanf(“%s”, s1->name); } User Defined Data Types - updated NI@2006 19
  20. 20. Example Using Structure: Call by reference#include <stdio.h>#include <string.h>struct student{ char name[20]; int id;};void Read (struct student * ); /* function prototype*/void main(void){ struct student student1; Read(&student1); /* function call: passing reference */ printf("Name: %s", student1.name); printf("nID: %dn", student1.id);}void Read (struct student *s1 ) /* function header, receive structure as a pointer variable*/{ printf("Enter name:"); scanf("%s",s1->name); /* you can also use: gets(s1->name) */ printf("Enter ID:"); scanf("%d",&s1->id);} User Defined Data Types - updated NI@2006 20
  21. 21. Using typedef in Structure DeclarationsThe keyword typedef provides amechanism for creating synonyms(aliases) for previously defined datatypes.Here is an example on how to usetypedef when declaring a structure: struct student { char name[20]; int studentID; char major[50]; struct address addr; }; User Defined Data Types - updated NI@2006 21
  22. 22. By using typedef: typedef struct student StudentData; we are now aliasing the structure with aname to be used throughout the program. Soinstead of writing the word “struct” beforedeclaring a struct variable like the following struct student my_student;we can now write: StudentData my_student;We could use the alias name when passingthe structure to a function: void display(StudentData s1); User Defined Data Types - updated NI@2006 22
  23. 23. Example : using typedef#include <stdio.h>#include <string.h>struct student{ char name[20]; int id;};typedef struct student StudentData;void display( StudentData ); /* function prototype */void main(void){ StudentData student1; strcpy(student1.name, "Ahmad"); student1.id = 12345; display(student1);}void display( StudentData s1){ printf("Name: %sn", s1.name); printf("ID: %dn", s1.id);} User Defined Data Types - updated NI@2006 23
  24. 24. Example: Array of structure#include <stdio.h>#define NUM_STUDENTS 10struct student { int studentID; char name[20]; int score; char grade;};typedef struct student StudentData;void Read (StudentData student[]);void CountGrade (StudentData student[]);void main ( ){ StudentData student[NUM_STUDENTS]; Read(student); CountGrade(student);} User Defined Data Types - updated NI@2006 24
  25. 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"); }} User Defined Data Types - updated NI@2006 25
  26. 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 %cn", student[i].name,student[i].grade); printf("n"); }} User Defined Data Types - updated NI@2006 26
  27. 27. /* Sample OutputEnter the studentID: 789654Enter the name: SalmanEnter the score: 96Enter the studentID: 741258Enter the name: JackEnter the score: 79:::The grade for Salman is AThe grade for Jack is C::Press any key to continue*/ User Defined Data Types - updated NI@2006 27
  28. 28. Example#include <stdio.h>struct car{ char maker[20]; char model[20]; int year;};void input(struct car*);void output(char*, char*, int*);void main(){ struct car firstcar; input (&firstcar); output(firstcar.maker, firstcar.model,&firstcar.year); printf("End of my act!n");} User Defined Data Types - updated NI@2006 28
  29. 29. void input(struct car *sp){printf("What is the maker of your car? ");gets(sp->maker);printf("What is the model of your car? ");gets(sp->model);printf("What year is your car? ");scanf("%d", &sp->year);}void output(char *sp1, char*sp2, int*sp3){printf("Your car is : %s, %s, %dn", sp1, sp2, *sp3);printf("Nice carn");} User Defined Data Types - updated NI@2006 29
  30. 30. /* Sample outputWhat is the maker of your car? HondaWhat is the model of your car? StreamWhat year is your car? 2003Your car is : Honda, Stream, 2003Nice carEnd of my act!Press any key to continue*/ User Defined Data Types - updated NI@2006 30
  31. 31. Enumeration ConstantsAn enumeration, introduced by the keywordenum, is a set of integer constants representedby 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. User Defined Data Types - updated NI@2006 31
  32. 32. If we want the enumeration to start with avalue other than 0, we can assign the value tothe 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 anenum can be used, a variable needs to bedeclared: enum islamic_months months; User Defined Data Types - updated NI@2006 32
  33. 33. There are cases where it is appropriate for usto use an enum. This is an example of such acase: enum islamic_months months; GetMonth (&months); switch (months) { case muharam: . . . break; case safar: . . . break; . . . } User Defined Data Types - updated NI@2006 33
  34. 34. This is another case where it is appropriate touse 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”); } User Defined Data Types - updated NI@2006 34
  35. 35. #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”, month, monthName[month-1]);} User Defined Data Types - updated NI@2006 35
  36. 36. Output:1 January2 February3 March4 April5 May6 June7 July8 August9 September10 October11 November12 December User Defined Data Types - updated NI@2006 36
  37. 37. SUMMARYIn this chapter you have learnt about Structure type and variable declarations How structure members can be accessed How structure can be initialized Passing structure to function Enumeration T.H.E E.N.D User Defined Data Types - updated NI@2006 37
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×