User Defined Data Types - updated Chapter 10: User Defined Data Types Objectives: In this chapter you will learn about, Introduction Declaring.

Slides:



Advertisements
Similar presentations
Chapter 7: Arrays In this chapter, you will learn about
Advertisements

2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Structures –Collections of related.
EASTERN MEDITERRANEAN UNIVERSITY EENG212 ALGORITHMS & DATA STRUCTURES Structures in C.
Chapter 10 C Structures, Unions, Bit Manipulations and Enumerations Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc.
Chapter 10 C Structures, Unions, Bit Manipulations, and Enumerations.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Structures Functions and Arrays Dale Roberts, Lecturer Computer.
C Language.
শিক্ষা মেলুক ডানা, আমাদের ভাষাতেই ! C Programming এর হাতেখড়ি পর্ব ১৪.
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Structures. An array allows us to store a collection of variables However, the variables must be of the same type to be stored in an array E.g. if we.
Enumerated data type & typedef. Enumerated Data Type An enumeration consists of a set of named integer constants. An enumeration type declaration gives.
ENUMERATED, typedef. ENUMERATED DATA TYPES An enumeration consists of a set of named integer constants. An enumeration type declaration gives the name.
True or false A variable of type char can hold the value 301. ( F )
 2000 Prentice Hall, Inc. All rights reserved. Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 10 - C Structures, Unions, Bit Manipulations,
Topic 11 – Structures and Unions. CISC105 – Topic 11 Introduction to Structures We have seen that an array is a list of the same type of elements. A structure.
Enum, Struct, & Union typedef - a type definition, typedef, gives a name to a data type by creating a new type that can then be used anywhere a type is.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Lecture No: 16. The scanf() function In C programming language, the scanf() function is used to read information from standard input device (keyboard).
Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because.
1 Chapter 10 Various Topics User defined Types Enumerated Types Type Casting Syntactic Sugar Type Coercion.
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: Arrays.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
CCSA 221 Programming in C CHAPTER 14 MORE ON DATA TYPES 1 ALHANOUF ALAMR.
ARRAY Prepared by MMD, Edited by MSY1.  Introduction to arrays  Declaring arrays  Initializing arrays  Examples using arrays  Relationship with pointers.
Programming in C Structs and Unions. Java vs C Suppose you were assigned a write an application about points and straight lines in a coordinate plane.
Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR.
1 Structures UniMAP SEM I - 11/12EKT 120 Computer Programming.
Chapter 8: Arrays Introduction to arrays Declaring arrays Initializing arrays Examples using arrays Relationship with pointers Array passing to a function.
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
Spring 2005, Gülcihan Özdemir Dağ Lecture 11, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 11 Outline 11.1.
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Programming Fundamentals. Today’s Lecture The Conditional Operator Logical Operators Structures Enumerations.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
Principles of Programming - NI Chapter 6: Function In this chapter, you will learn about Introduction to function User define function Function prototype.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 7: Pointers.
Chapter 10 Structures, Unions, Bit Manipulations, and Enumerations Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering.
+ Structures and Unions. + Introduction We have seen that arrays can be used to represent a group of data items that belong to the same type, such as.
CCSA 221 Programming in C CHAPTER 9 WORKING WITH STRUCTURES 1.
Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function.
1 EPSII 59:006 Spring HW’s and Solutions on WebCT.
Structures. Outline Introduction Structure Definitions and declarations Initializing Structures Operations on Structures members Structures as Functions.
CHAPTER 7: Arrays CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (Feb 2012)
Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays.
1. 2 Introduction Structure Definitions and Declarations Initializing Structures Operations on Structures Members Structures as Functions Parameters Array.
Introduction to Computers and Programming Class 24 Structures (structs) Professor Avi Rosenfeld.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 11: Structured Data.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 11: Structured Data.
1 Lecture10: Structures, Unions and Enumerations 11/26/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
STRUCTURES. INTRODUCTION A structure is same as that of records. It stores related information about an entity. Structure is basically a user defined.
What do I need to Know For My Assignment?. C Pointer Review To declare a pointer, we use the * operator. This is similar to but different from using *
Lecture 10: Structures. Outline Introduction Structure Definitions and declarations Initializing Structures Operations on Structures members Structures.
1 Chapter 10 & 11 enum & Structured Types Dale/Weems.
User Defined Data Types
CS1010 Programming Methodology
Structure, Unions, typedef and enumeration
C Structures, Unions, Bit Manipulations and Enumerations
Lecture 13 Structs.
C Structures, Unions, and Enumerations
Programming in C #4 Structs and Unions.
C Structures, Unions, Bit Manipulations and Enumerations
Derived types.
C Structures, Unions, Bit Manipulations and Enumerations
CS 240 – Lecture 7 Boolean Operations, Increment and Decrement Operators, Constant Types, enum Types, Precedence.
Structures, Unions, and Enumerations
Presentation transcript:

User Defined Data Types - updated Chapter 10: 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

User Defined Data Types - updated 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.

User Defined Data Types - updated Definition A structure is a derived data type that represents a collection of a related data items called components (or members) that are not necessarily of the same data type.

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

User Defined Data Types - updated 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;

User Defined Data Types - updated 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 Structure variableComponentsValues name major studentID Simon 0078 CS my_student Conceptual memory structure variable my_student of type student (assuming that the components of variable my_student have already been assigned values)

User Defined Data Types - updated 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 { char name[20]; int studentID; char major[50]; }; struct student my_student; struct student { char name[20]; int studentID; char major[50]; } my_student; =

User Defined Data Types - updated 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 is a member of struct type student: struct address { int no; char street[20]; int zipcode; };

User Defined Data Types - updated We can rewrite the structure student declaration as follow: This structure type student can be written as; struct student { char name[20]; int studentID; char major[50]; struct address addr; } ;

User Defined Data Types - updated struct student { char name[20]; int studentID; char major[50]; struct address{ int no; char street[20]; int zipcode; };

User Defined Data Types - updated Referring and Initializing Structure Elements A structure contains many elements. Each elements of a structure can be referred to / accessed by using the component selection operator “.” (dot). Let us use the structure student which we have seen before as an example: Therefore to refer to the element of a structure, we may write as follow; my_student.name; my_student.studentID; my_student.major; struct student { char name[20]; int studentID; char major[50]; }; struct student my_student;

User Defined Data Types - updated Therefore, we can initialize each elements of a structure individually such as: struct student my_student; my_student.studentID = 10179; 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.

User Defined Data Types - updated Example struct birthdate { int month; int day; int year; }; 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

User Defined Data Types - updated Passing Structures to a Function Call 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 Example Using Structure: Call by value #include 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: %s\n", s1.name); printf("ID: %d\n", s1.id); }

User Defined Data Types - updated Example Using Structure: A Function that return a structure #include 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: %d\n", 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 Call by reference 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. 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 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 (indirect component selection operator). For example: void Read(struct student *s1) { s1->studentID = 10179; scanf(“%s”, s1->name); }

User Defined Data Types - updated Example Using Structure: Call by reference #include 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: %d\n", 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 Using typedef in Structure Declarations The keyword typedef provides a mechanism for creating synonyms (aliases) for previously defined data types. Here is an example on how to use typedef when declaring a structure: struct student { char name[20]; int studentID; char major[50]; struct address addr; } ;

User Defined Data Types - updated By using typedef: typedef struct student StudentData; we are now aliasing the structure with a name to be used throughout the program. So instead of writing the word “struct” before declaring a struct variable like the following struct student my_student;  we can now write: StudentData my_student; We could use the alias name when passing the structure to a function: void display(StudentData s1);

User Defined Data Types - updated #include 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: %s\n", s1.name); printf("ID: %d\n", s1.id); } Example : using typedef

User Defined Data Types - updated Example: Array of structure #include #define NUM_STUDENTS 10 struct 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 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 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"); }

User Defined Data Types - updated /* Sample Output Enter the studentID: Enter the name: Salman Enter the score: 96 Enter the studentID: Enter the name: Jack Enter the score: 79 : The grade for Salman is A The grade for Jack is C : Press any key to continue */

User Defined Data Types - updated Example #include 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 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, %d\n", sp1, sp2, *sp3); printf("Nice car\n"); }

User Defined Data Types - updated /* Sample output What is the maker of your car? Honda What is the model of your car? Stream What year is your car? 2003 Your car is : Honda, Stream, 2003 Nice car End of my act! Press any key to continue */

User Defined Data Types - updated Enumeration Constants 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.

User Defined Data Types - updated 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;

User Defined Data Types - updated 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;... }

User Defined Data Types - updated 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”); }

User Defined Data Types - updated #include 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 Output: 1January 2February 3March 4April 5May 6June 7July 8August 9September 10October 11November 12December

User Defined Data Types - updated SUMMARY In 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