Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
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.
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 এর হাতেখড়ি পর্ব ১৪.
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
Programming and Data Structure
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
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.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
Enumerated Types 4 Besides the built-in types, ANSI C allows the definition of user-defined enumerated types –To define a user-define type, you must give.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 10 - C Structures, Unions, Bit Manipulations,
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.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
Data Type. A data type defines a set of values that a variable can store along with a set of operations that can be performed on that variable. Common.
Lecture No: 16. The scanf() function In C programming language, the scanf() function is used to read information from standard input device (keyboard).
Multidimensional Arrays C++ also allows an array to have more than one dimension. For example, a two-dimensional array consists of a certain number of.
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.
21 August (B.V.Patel institute of BMC & IT) STRUCTURE AND UNIONS.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
CCSA 221 Programming in C CHAPTER 14 MORE ON DATA TYPES 1 ALHANOUF ALAMR.
C Tokens Identifiers Keywords Constants Operators Special symbols.
J-1 University of Washington Computer Programming I Switch Statement © 2000 UW CSE.
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.
9. Types Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 1 Data Types data type:a collection of.
Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR.
User Defined Data Types - updated Chapter 10: User Defined Data Types Objectives: In this chapter you will learn about, Introduction Declaring.
Chapter 8: Arrays Introduction to arrays Declaring arrays Initializing arrays Examples using arrays Relationship with pointers Array passing to a function.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
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.
Date processing and conversion Please use speaker notes for additional information!
 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’};
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
Chapter 2 Section 2.1 Sets and Set Operations. A set is a particular type of mathematical idea that is used to categorize or group different collections.
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.
1 Homework –Continue Reading K&R Chapter 2 –We’ll go over HW2 at end of class today –Continue working on HW3 Questions?
1 EPSII 59:006 Spring HW’s and Solutions on WebCT.
Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays.
CCSA 221 Programming in C CHAPTER 11 POINTERS ALHANOUF ALAMR 1.
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 *
1 Chapter 10 & 11 enum & Structured Types Dale/Weems.
13 Arrays CE : Fundamental Programming Techniques June 161.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
User Defined Data Types
Chapter 10-1: Structure.
Structure, Unions, typedef and enumeration
C Programming Tutorial – Part I
C Structures, Unions, Bit Manipulations and Enumerations
DATA HANDLING.
C Structures, Unions, and Enumerations
Programming in C #4 Structs and Unions.
Programming in C 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.
Programming Language C Language.
Structures, Unions, and Enumerations
Presentation transcript:

Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function Using typedef Example using structure Enumeration constants

Introduction So far we have only used data types which have been defined by C such as int, double, char and etc. It is also possible to create our own data types - user defined data type. We must declare data types as structures or 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.

Structure Definition General syntax: struct structure_name { data_type element1; data_type element2;... }; Example: Structure definition: struct student { char name[20]; int studentID; char major[50]; }; Structure variable declarartion: struct student my_student;

Structure Definition Example: struct student { char name[20]; int studentID; char major[50]; } my_student;

Nested Structure struct address { char address1[50]; char address2[50]; int postcode; char town[50]; char state[50]; }; struct student { char name[20]; int studentID; char major[50]; struct address addr; } my_student;

struct student { char name[20]; int studentid; char major[50]; struct address { char address1[50], address2[50], town[50], state[50]; int postcode; } addr; }; struct student my_student;

Referring and Initializing Structure Elements A structure contains many elements. Each elements of a structure can be referred to by using the operator “.” Let us use the structure student which we have seen before as an example: struct student my_student; my_student.name; my_student.studentID;

Therefore, we can initialize each elements of a structure individually such as: struct address my_addr={“xxxx”,”yyy”,123,”Bangi”,”selangor”}; struct student my_student; my_student.studentID = 10179; my_student.addr = my_addr; Or we can initialize the structure while we are creating an instance of the structure: struct address my_addr ={“xxxx”,”yyy”,123,”Bangi”,”selangor”}; ; struct student my_student = {“Salman”, 10179, “IT”, my_addr} 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.

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.

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); }

Passing Structures to a Function #include typedef struct student{ int studentid; char name[20]; int score; char grade; } StudentData; void DecideGrade(StudentData *); void main(){ StudentData x; scanf(“%d%s%d”, &x.studentid, x.name, &x.score); DecideGrade(&x); printf(“The grade is %c\n”, x.grade); } void DecideGrade(StudentData *p) { if(p->score>90) p->grade=‘A’; else if(p->score>80) p->grade=‘B’; else if(p->score>70) p->grade=‘C’; else if(p->score>60) p->grade=‘D’; else p-<grade=‘F’; }

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: typedef struct student { char name[20]; int studentID; char major[50]; struct address addr; } StudentData;

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);

Example Using Structure #include #define NUM_STUDENTS 20 typedef struct student { int studentID; char name[30]; int score; char grade; } StudentData; void main(void) { StudentData students[NUM_STUDENTS]; int i; Read(students); DecideGrade(students); }

void Read(StudentData students[]) { int i; for (i = 0; i < NUM_STUDENTS; i++) { printf(“Enter the studentID: “); scanf(“%d”, &students[i].studentID); printf(“Enter the name: “); scanf(“%s”, students[i].name); printf(“Enter the score: “); scanf(“%d”, &students[i].score); } void DecideGrade(StudentData students[]) { int i; for (i = 0; i < NUM_STUDENTS; i++) { if (students[i].score > 90) students[i].grade = ‘A’; else if (students[i].score > 80) students[i].grade = ‘B’; else if (students[i].score > 65) students[i].grade = ‘C’; else if (students[i].score > 50) students[i].grade = ‘D’; else students[i].grade = ‘F’; }

Enumerations An enumeration, introduced by the keyword enum, is a set of integer constants represented by identifiers. Example: typedef enum islamic_months { muharam, safar, rabiulawal, rabiulakhir, jamadilawal, jamadilakhir, rejab, syaaban, ramadhan, syawal, zulkaedah, zulhijjah } ISLAMIC_CAL; Each of the identifiers actually has a value, starting with 0 (unless specified otherwise). Therefore, we can treat them as integers.

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; ISLAMIC_CAL months;

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;... }

This is another case where it is appropriate to use an enum: enum Boolean {FALSE, TRUE}; void main(void) { int list[], target; enum Boolean found; Read(list); scanf(“%d”, &target); found = Search(list, target); if (found == TRUE) printf(“FOUND!!”); else printf(“Cannot find the requested item”); }

#include typedef enum months {JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC} MONTH; void main(void) { MONTH month; char *monthsName[12] = {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”}; for (month = JAN; month <= DEC; month++) printf(“%s %s”, month, monthsName[month-1]); } Output: JANJanuary FEBFebruary MARMarch etc

Unions A union allows you to handle an area of memory that could contain different types of variables. The syntax for unions is identical to that for structures. You can use either typedef's or instream definitions: simply replace the word struct with the word union. You can contain unions within structures, or structures within unions. Either way, the C union is an unwieldy mechanism. A union might be used to group different record layouts from the same file, or to handle a single field that could contain, for example, either numeric or character data.

Unions Example typedef struct transaction { int amount; union { int count; char name[4]; } udata; char discount; } Transaction;

Unions The fields in this structure are referred to as follows: Transaction trans; trans.amount = 0; trans.udata.count = 0; trans.discount = 'N'; //trans.udata.name = “ali”; Just as in any other language, it's up to you to determine what kind of variable is present in any instance.

Unions Using Structures within Unions: Unions can contain any types of variables, including structures. Be aware that the length of a union is the length of its longest variable. If the name in the previous example had only been 3 characters long, there would have been an undefined slack byte after name, since an integer occupies 4 bytes. If you have a more complex situation than a simple redefine of one scalar variable with another, you may need to use structures in the union. Let's say an area in the record could contain either one long integer or two short integers; one solution would be to define a structure for the two shorts.

Unions typedef struct twoshorts { short smallamount1; short smallamount2; } TwoShorts; typedef union udata { TwoShorts smallamounts; int bigamount; } Udata;