C Programming Lecture 23 Enumeration Types Structures.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

1 Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure Definitions 10.3Initializing Structures 10.4Accessing.
StructuresStructures Systems Programming. Systems Programming: Structures 2 Systems Programming: 2 StructuresStructures Structures Structures Typedef.
StructuresStructures Systems Programming. StructuresStructures Structures Structures Typedef Typedef Declarations Declarations Using Structures with Functions.
2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
2000 Prentice Hall, Inc. All rights reserved. 1 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 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.
Programming in C Chapter 10 Structures and Unions
1 Structures. 2 Structure Basics A structure is a collection of data values, called data members, that form a single unit. Unlike arrays, the data members.
Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
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.
Data Structures Using C++ 2E
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.
Structures, Unions, and Typedefs CIS 1057 Fall Structures, Unions, and Typedefs CIS 1057 Computer Programming in C Fall 2013 (Many slides based on/borrowed.
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.
1 Types The type of a variable represents a set of values that may be assigned to the variable. For example, an integer variable is one that may take the.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 10 - C Structures, Unions, Bit Manipulations,
Structures, Unions, and Typedefs CS-2301 D-term Structures, Unions, and Typedefs CS-2301 System Programming D-term 2009 (Slides include materials.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
Structures and UnionsCS-2301 B-term Structures and Unions CS-2301, System Programming for Non-majors (Slides include materials from The C Programming.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
Structures, Unions, and Typedefs CS-2303, C-Term Structures, Unions, and Typedefs CS-2303 System Programming Concepts (Slides include materials from.
1 Structures. 2 C gives you several ways to create a custom data type. –The structure, which is a grouping of variables under one name and is called an.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations System-oriented Programming, B. Hirsbrunner,
Data Types.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
CCSA 221 Programming in C CHAPTER 14 MORE ON DATA TYPES 1 ALHANOUF ALAMR.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 10 - C Structures, Unions, Bit Manipulations,
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 23P. 1Winter Quarter Structs and Enumeration Lecture 23.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
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.
16. STRUCTURES, UNIONS, AND ENUMERATIONS. Declaring Structures A structure is a collection of one or more components (members), which may be of different.
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Programming Fundamentals. Today’s Lecture The Conditional Operator Logical Operators Structures Enumerations.
Data Structure and c K.S.Prabhu Lecturer All Deaf Educational Technology.
Pointers. Pointer Variable Declarations and Initialization Pointer variables – Contain memory addresses as their values – Normal variables contain a specific.
C Lecture Notes 1 Structures & Unions. C Lecture Notes Introduction Structures –Collections of related variables (aggregates) under one name Can.
Chapter 10 Structures, Unions, Bit Manipulations, and Enumerations Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering.
CPS120: Introduction to Computer Science Lecture 15A Structures.
Pointers *, &, array similarities, functions, sizeof.
CPT: Types/ Computer Programming Techniques Semester 1, 1998 Objective of these slides: –to look at how new types can be created 6. User-defined.
1 EPSII 59:006 Spring HW’s and Solutions on WebCT.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
Enumerated Types Mr. Dave Clausen La Cañada High School.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
 2000 Prentice Hall, Inc. All rights reserved Introduction Structures –Collections of related variables (aggregates) under one name Can contain.
StructureStructure. Outline Introduction Structure Definitions Initializing Structures Accessing Members of Structures Using Structures with Functions.
COMP102 Lab 111 COMP 102 Programming Fundamentals I Presented by : Timture Choi.
Chapter 6. Character String Types It is one in which the values consists of sequences of characters. How to Define a variable contain a string? In a programming.
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 *
10 주 강의 Bitwise operators and Enumeration types. 컴퓨터환경 8-bit bytes, 4-bytes words Two ’ s complement ASCII character codes.
Java Programming Language Lecture27- An Introduction.
Records type city is record -- Ada Name: String (1..10); Country : String (1..20); Population: integer; Capital : Boolean; end record; struct city { --
LESSON 06.
Structure, Unions, typedef and enumeration
Enumeration Types and typedef
Instructor: Ioannis A. Vetsikas
C Structures, Unions, Bit Manipulations and Enumerations
Types and Classes in Haskell
CS 240 – Lecture 7 Boolean Operations, Increment and Decrement Operators, Constant Types, enum Types, Precedence.
Structures.
Presentation transcript:

C Programming Lecture 23 Enumeration Types Structures

b Enumeration types are defined and used by the programmer as the need arises. They allow the programmer to name a finite set together with its elements.They allow the programmer to name a finite set together with its elements. –The elements of the finite set are called enumerators.

Naming a Finite Set and Declaring Enumerators enum day {sun, mon, tue, wed, thu, fri, sat}; The keyword enum is used to declare an enumeration type. The enumerators above are the identifiers sun, mon,...,sat. The keyword enum along with the tag name day are used as a type specifier to declare variables of type enum day. enum day d1, d2; /* declares variables d1 & d2 */

Alternative for Declaring Variables b On the previous slide, the enumeration type enum day was first declared, then variables of that type were declared. We can do both at the same time.We can do both at the same time. enum day {sun,mon, tue, wed, thu, fri, sat} d1, d2;

What are the Enumerators, Really? enum day {sun, mon, tue, wed, thu, fri, sat} d1; b The enumerators sun, mon,..., sat are identifiers: They are constants of type int.They are constants of type int. By default, the first one is given the value 0, and each succeeding one has the next integer.By default, the first one is given the value 0, and each succeeding one has the next integer.

Initialization of Enumerators enum fruit {apple = 7,pear, orange = 3,lemon} fruit; enum fruit {apple = 7,pear, orange = 3,lemon} fruit; Since the enumerator apple has been initialized to 7, pear has a value of 8. Since the enumerator apple has been initialized to 7, pear has a value of 8. Since orange has a value of 3, lemon has a value of 4. Since orange has a value of 3, lemon has a value of 4.

Using Enumeration Variables b The previously declared variables d1 and d2 can only be assigned values from the set we named day. d1 = fri; d2 = sat;

Using Enumeration Types b Enumerators are treated as programmer- specified constants and used to aid program clarity. If necessary, the underlying value can be obtained by using a cast.If necessary, the underlying value can be obtained by using a cast. The variables and enumerators in a function must all have distinct values.The variables and enumerators in a function must all have distinct values.

The typedef Facility C provides the typedef facility so that a descriptive identifier can be used as the name of a specific type. typedef int color; typedef int color; This makes color a type that is synonymous with int, and color can now be used as a type in declarations. color red, green, blue; color red, green, blue;

Leaving off the Tag Name enum tree_type {fir,pine} tree; We can leave out the tag name, but all variables will have to be declared when the enumeration is declared: We can leave out the tag name, but all variables will have to be declared when the enumeration is declared: enum {fir,pine} tree;

Style Since enumerators can be mnemonic (descriptive),their use tends to be self-documenting and is considered good programming style. b Examples enum bool {false, true};enum bool {false, true}; enum off_on {off, on};enum off_on {off, on}; enum no_yes {no, yes};enum no_yes {no, yes}; enum speed {slow, fast};enum speed {slow, fast};

The Structure Type b The structure type allows the programmer to aggregate components into a single, named variable. A structure has components that are individually named.A structure has components that are individually named. –These components are called members. The members of a structure can be of various types.The members of a structure can be of various types. –This allows the programmer to create aggregates of data that are suitable for each specific problem. Like arrays and pointers, structures are considered a derived type.Like arrays and pointers, structures are considered a derived type.

The Member and Structure Pointer Operators. and -> b Members of structures are accessed using either: the member operator. orthe member operator. or the structure pointer operator ->the structure pointer operator -> b These operators along with () and [] have the highest precedence.

Declaring Structures b Example Using Playing Cards Playing cards have what is known as a pip value and a suit value.Playing cards have what is known as a pip value and a suit value. –The three of spades has a pip value, 3 and a suit value, spades. b We can declare the structure type: struct card { struct card { int pips; int pips; char suit; char suit; }; }; to capture the information needed to represent a playing card. to capture the information needed to represent a playing card.

The Derived Type struct card struct card { int pips; int pips; char suit; char suit;}; b struct is a keyword. b card is the structure tag name. b pips is a member variable that will take values from 1 to 13. b suit is a member variable that will take values from c, d, h, and s,representing clubs, diamonds, hearts, and spades.

Declaring Variables of the Derived Type struct card b The declaration struct card c1, c2; allocates space for the identifiers c1 and c2, which are of type struct card. b To access the members of c1 and c2, we use the structure member operator.: c1.pips = 5; /* a construct of the form */ c1.suit = d; /* structure_variable.member_name */ c2.pips = 12; /* is used as a variable in the */ c2.suit = s; /* same way a simple variable or */ /* an element of an array is used.*/ /* an element of an array is used.*/

Uniqueness of Member Names b A member name must be unique within a specified structure. b Since the member must always be prefaced or accessed through a unique structure variable identifier, there is no confusion between members of different structures having the same name.

Example of Same Member Names in Different Structures struct fruit { char name[15]; char name[15]; int calories; int calories;}; struct vegetable { char name[15]; char name[15]; int calories; int calories;} struct fruit a; struct vegetable b; We can access a.calories and b.calories without ambiguity.

Declaration of Variables During the Creation of a Structure Type b It is possible to create a structure type and declare variables of that type at the same time. struct card { int pips; int pips; char suit; char suit; } c, deck[52]; /* c is a variable that can */ } c, deck[52]; /* c is a variable that can */ /* store a single card. deck */ /* store a single card. deck */ /* is the name of an array */ /* is the name of an array */ /* that can store a deck of */ /* that can store a deck of */ /* cards. */ /* cards. */

Omission of the Tag Name struct {/* Since no tag name is */ char *last_name;/* used, no variables can */ char *last_name;/* used, no variables can */ int student_id; /* be declared later in */ int student_id; /* be declared later in */ char grade;/* the program. */ char grade;/* the program. */ } s1, s2, s3; struct student { /* Variables can now be */ char *last_name;/* be declared later in */ char *last_name;/* be declared later in */ int student_id;/* the program as shown */ int student_id;/* the program as shown */ char grade;/* below. Until the */ char grade;/* below. Until the */ };/* declaration below, no */ /* storage is allocated. */ /* storage is allocated. */ struct student temp, class[100];

Example: class_info.c b See the class_info files in the public subdirectory class23. Note: The structure member last_name is declared as last_name[20]; instead of *last_name so that the name can be read in from a file rather than being a constant in the program;Note: The structure member last_name is declared as last_name[20]; instead of *last_name so that the name can be read in from a file rather than being a constant in the program; The 20 can be any number that is large enough to hold the characters of a name and the null character \0.The 20 can be any number that is large enough to hold the characters of a name and the null character \0.

The Structure Pointer Operator -> b C provides the structure pointer operator -> to access members of a structure via a pointer. -> is typed on the keyboard as a minus sign followed by a greater than sign.-> is typed on the keyboard as a minus sign followed by a greater than sign. b If a pointer variable is assigned the address of a structure, then a member of the structure can be accessed by: pointer-to-structure -> member_name An equivalent construct is: (*pointer_to_structure).member_name

Examples of the Two Accessing Modes Declarations and Assignments struct student temp, *p = &temp; temp.grade = A; temp.last_name = Bushker; temp.student_id = ; Expression Equivalent Expression Conceptual Value temp.gradep -> grade A temp.last_namep -> last_nameBushker temp.student_idp -> student_id (*p).student_idp -> student_id590017

Operators Associativity () []. -> ++ (postfix) -- (postfix)left to right ++ (prefix) -- (prefix) ! ~ sizeof(type)right to left + (unary) - (unary) & (address) * (dereference) */%left to right + -left to right + -left to right >left to right >left to right >= left to right >= left to right == != left to right == != left to right &left to right &left to right ^left to right ^left to right |left to right |left to right &&left to right &&left to right ||left to right ||left to right ?:right to left ?:right to left = += -= *= /= %= >>= >= <<= &= ^= |= right to left, (comma operator)left to right, (comma operator)left to right Precedence and Associativity

Structures as Arguments to Functions b Traditional C allows a pointer to a structure type to be passed as an argument to a function and returned as a value. b ANSI C also allows structures themselves to be passed as arguments to functions and returned as values (as a complete structure). However, a pointer to a structure is still the preferred type of function argument and return value in most cases.However, a pointer to a structure is still the preferred type of function argument and return value in most cases.

Example of Passing a Pointer to a Structure Type struct card { int pips; int pips; char suit; char suit;};... struct card c; int pip = 12; /* the Queen of Hearts */ char suit = h;... assign_values(&c, pip, suit); /* Function Call */... void assign_values(struct card *c_ptr, int p, char s); { c_ptr->pips = p; c_ptr->pips = p; c_ptr->suit = s; c_ptr->suit = s;}

Assignment of Structures b ANSI C also allows assignment of structures. If a and b are variables of the same structure type, the assignment expression a = b is allowed.If a and b are variables of the same structure type, the assignment expression a = b is allowed. See the assignment to an array of struct student types in the public subdirectory file class23 for an example of assignment of structures.See the assignment to an array of struct student types in the public subdirectory file class23 for an example of assignment of structures. Look in class23 and study the programs there.Look in class23 and study the programs there.

Data Structures b In C, structures, pointers, and arrays may be combined to create complicated data structures. We have entire courses on this.We have entire courses on this. b Problem solving is enhanced by matching a data structure to the information that is to be manipulated. In C, struct is an encapsulation mechanism for a set of characteristics that describe a real- world object such as a student.In C, struct is an encapsulation mechanism for a set of characteristics that describe a real- world object such as a student.

Initialization of Structures b All external and static variables, including structure variables, that are not explicitly initialized are initialized by the system. b We can also initialize automatic structures. Similar to initializing an automatic array.Similar to initializing an automatic array.

Example of Initializing Automatic Structure Variables struct card { struct card { int pips; char suit; }; struct fruit { char name[15]; int calories; };... struct card c = {12, s}; struct fruit frt = {plum, 150};

The Use of typedef b The typedef facility is often used to rename a structure type. We will see examples of this when we look at linked lists.We will see examples of this when we look at linked lists.