Chapter 10 C Structures, Unions, Bit Manipulations

Similar documents
Fundamentals of Programming. Lecture 12: C Structures, Unions, Bit Manipulations and Enumerations

Programming for Engineers Structures, Unions

OBJECT ORIENTED PROGRAMMING USING C++

typedef int Array[10]; String name; Array ages;

Fundamentals of Programming Session 24

Darshan Institute of Engineering & Technology for Diploma Studies Unit 5

Introduction. Structures, Unions, Bit Manipulations, and Enumerations. Structure. Structure Definitions

IV Unit Second Part STRUCTURES

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -STRUCTURE- SPRING 2015 SEON-JU AHN, CNU EE

Fundamental of Programming (C)

Pointers and Structure. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

CS132 Algorithm. Instructor: Jialiang Lu Office: Information Center 703

CS561 Manju Muralidharan Priya Structures in C CS200 STRUCTURES. Manju Muralidharan Priya

UNIT-V. Structures. The general syntax of structure is given below: Struct <tagname> { datatype membername1; datatype membername2; };

C PROGRAMMING Lecture 4. 1st semester

Chapter 7: Structuring the Data. Lecture7 1

Chapter 8 STRUCTURES IN C

Structures. Today s Goals. Structure Operations. Structure Type Declaration. Struct Instance. typedef. CS246 Lec12. Structures

Structures and Unions in C. Alan L. Cox

Data Representation and Storage

Dept. of Computer and Information Science (IDA) Linköpings universitet Sweden

BLM2031 Structured Programming. Zeyneb KURT

CHAPTER 4 Structures

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

A Fast Review of C Essentials Part I

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Tin học cơ sở 4$ Structures!

Student Name: (in Capital Letters) CSE Introduction to Programming for Engineers and Scientists. Final Exam

by: Lizawati, Norhidayah & Muhammad Noorazlan Shah Computer Engineering, FKEKK, UTeM

Programming in C. What is C?... What is C?

Downloaded S. from Kiran, PGT (CS) KV, Malleswaram STRUCTURES. Downloaded from

CS Programming In C

Structures and Union. Fall Jinkyu Jeong GEBD029: Basis and Practice in Programming Fall 2014 Jinkyu Jeong

User Defined data Types

Input And Output of C++

ALQUDS University Department of Computer Engineering

Compiling and Running a C Program in Unix

Relationship between Pointers and Arrays

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University

C Structures Self-referencing Card Shuffling Unions. C Structures CS Prof. Jonathan Ventura. Prof. Jonathan Ventura C Structures

Programming in C. What is C?... What is C?

CSE 230 Intermediate Programming in C and C++

Programming in C UVic SEng 265

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

Example: Structure, Union. Syntax. of Structure: struct book { char title[100]; char author[50] ]; float price; }; void main( )

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Programming. Structures, enums and unions

Structure, Union. Ashishprajapati29.wordpress.com. 1 What is structure? How to declare a Structure? Explain with Example

Programming 2. Object Oriented Programming. Daniel POP

Low-Level Programming in C

Structures. Lecture 15 COP 3014 Spring April 16, 2018

Structures Unions and Enumerated Datatypes 224

Data Structures Unit 02

Lab Session # 3 Conditional Statements. ALQUDS University Department of Computer Engineering

C LANGUAGE AND ITS DIFFERENT TYPES OF FUNCTIONS

M.EC201 Programming language

12 CREATING NEW TYPES

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Variables and Constants

Chapter-8 DATA TYPES. Introduction. Variable:

Type Definition. C Types. Derived. Function Array Pointer Structure Union Enumerated. EE 1910 Winter 2017/18

CS558 Programming Languages

3.3 Structures. Department of CSE

Lexical and Syntax Analysis

8. Structures, File I/O, Recursion. 18 th October IIT Kanpur

Chapter 11: Structured Data

Computer System and programming in C

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

Slide Set 6. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

.:: UNIT 1 ::. INTRODUCTION TO ALGORITHM & DATA STRUCTURES

Ch. 10: Name Control

F4104 ALGORITHM & DATA STRUCTURE

Programming in C. Pointers and Arrays

COMP322 - Introduction to C++

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

UNIT-IV. Structure is a user-defined data type in C language which allows us to combine data of different types together.

Syntax and Variables

C Programming for Engineers Functions

Structured Data. CIS 15 : Spring 2007

C Language, Token, Keywords, Constant, variable

Chapter-14 STRUCTURES

CS 31 Discussion 1A, Week 8. Zengwen Yuan (zyuan [at] cs.ucla.edu) Humanities A65, Friday 10:00 11:50 a.m.

Lexical and Syntax Analysis. Abstract Syntax

Chapter 7 C Pointers

The New C Standard (Excerpted material)

MYcsvtu Notes LECTURE 34. POINTERS

Binghamton University. CS-211 Fall Variable Scope

What is a Structure? related data items. Examples: n Used for handling a group of logically

Binghamton University. CS-211 Fall Variable Scope

High Performance Computing

Procedures, Parameters, Values and Variables. Steven R. Bagley

Data Representation and Storage. Some definitions (in C)

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

C: How to Program. Week /Mar/05

CS201 - Introduction to Programming Glossary By

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

Computer Systems Principles. C Pointers

Transcription:

Chapter 10 C Structures, Unions, Bit Manipulations Skipped! Skipped! and Enumerations Skipped!

Page 416 In programming languages, Arrays (Chapter 6) allows programmers to group elements of the same type under one name. C programming language also provides another tool for grouping elements together called Structures. Structures sometimes referred to as aggregates are collections of related variables grouped under one name. Structures may contain variables of many different data types in contrast to arrays that contain only elements of the same data type. Structures are commonly used to define records to be stored in files (see Chapter 11, C File Processing). Structures are very powerful concept that programmers use in many C programs.

10.2 Structure Definitions 1/3 Page 416 A structure is a derived data types and structures are defined by using struct statement. In order to understand the concept of structure, let s consider the definition of any point in Cartesian coordinates. In Cartesian coordinates any point can be described with two numbers corresponding x- and y-coordinates.**** Name Tag kind of structure struct point { int x; int y; }; Members of Structure Members are defined within braces as regular variable definitions. struct statement ends with ; as other statements in C Note: This is just the structure definition. Structure definitions doesn t consume any space on the memory. We will learn how to use the structures later in this chapter.

10.2 Structure Definitions 2/3 Page 416 Let s suppose that we are dealing with playing cards; each card can be represented by a face and suit.** Suit of the card: one of the following Hearths, Spades, Clubs, Diamonds Face of the Card: one of the following Ace, Two,., Jack, Queen, King We can define a structure with two members corresponding the suit and face of the card. Both variables can be considered as strings as below.

10.2 Structure Definitions 3/3 Page 416 Let s suppose that we are dealing with the employee records; employee s record contains information such as employee s first and last names, employee s age, 'M' or 'F' for the employee s gender and the employee s hourly salary. We can define a structure type with tag, employee. Employee Information: First Name : Character array Last Name : Character array Age : Integer Gender : A character Hourly Salary : Double

Understanding Structures Page 416 Let s suppose that we are dealing with dates (calendar date). Any date can be expressed by three integer numbers corresponding to day, month, and year as in dd/mm/yyyy. We can then define the structure with three members of integer types. struct date { int month; int day; int year; }; It is more suitable to define a structure with three members if you are dealing with bunch of dates as like (date of birth, date of marriage, date of manufacture, expiration date and so on ). After defining a structure, it becomes easier to deal data types grouped in a structure. Many more examples can be given on structures (e.g. time (hh:mm:ss).) Remember: Members of a structure can be primitive data types and as well as another structure.

Page 418 Structures can be initialized using initializer list similar to initialization of elements of an array. Let s now consider again a structure for date (dd/mm/yyyy) struct date /*Defining a Structure with date tag after include statements*/ { int day; int month; int year; }date1,date2; /* Defining Two Variables with this Structure Type*/ OR initialization can be done while defining the variables as below }date1, date2 = {{1,1,2013},{22,5,2013}; In the above initialization List: date1: (dd/mm/yyyy) members corresponds 1/1/2013 date2: (dd/mm/yyyy) members corresponds 22/5/2013

Page 418 Another way to define to initialize a structures is first the structure is defined then the object with this type is defined and initialized later in the main program. Let s now consider again a structure for date (dd/mm/yyyy) struct date /*Defining a Structure with date tag after include statements*/ { int day; int month; int year; }; /* No Variable IS DEFINED YET. */ LATER UNDER MAIN PROGRAM defining two structure Variable struct date date1,date2; OR UNDER MAIN PROGRAM defining two structure Variable and initializing struct date date1,date2 = {{1,1,2013},{22,5,2013}; In the above initialization List: date1: (dd/mm/yyyy) members corresponds 1/1/2013 date2: (dd/mm/yyyy) members corresponds 22/5/2013 Note: Because structure variables can be defined later in the program. It is highly recommended to using the structure tag although it is optional.

Page 418 So far, we have learned how to define a structure, but didn t talk about how to use it. In order to use structures, we should be able to access the members of the structure. Two operators are used to access members of structures: 1. The structure member operator (. ) also called dot operator. VariableName.MemberName 2. The structure pointer operator (->) also called arrow operator. It is possible define a pointer to a structure. -> is used to access the member of the structure variable via pointers. PointerName->MemberName

Structure Member Operator. Page 418 Let s now consider the date structure (mm/dd/yyyy) struct date{ /*Defining Structure Type*/ int month; int day; int year; }; struct date today; Members of the today structure variables can be accessed via. operator. We can print, read, or assign any value to members by accessing them using. operator. today.month = 9; today.day = 25; today.year = 2004; Below printf statement prints the date in (mm/dd/yyyy) format. printf( %d/%d/%d, today.month, today.day, today.year);

Structure Pointer Operator -> Page 418 Let s now consider the segment of program struct date{ /*Defining Structure Type*/ int month; int day; int year; }; struct date today={9,25,2004}; /* Initialized */ struct date *dateptr=today; /* Defining a Pointer to date Structure */ Members of Date Structure can be accessed in Different Ways The members of the today structure variable can be accessed by using. today.month, today.day, today.month They can be also accessible by using the dateptr pointer. dateptr->month dateptr->day dateptr->year OR also can be accessed via pointer but using. operator. Two are the Same (*dateptr).month (*dateptr). day (*dateptr). year

Accessing Structure Members Out of Book Below program demonstrates accessing members of a structure directly and via a pointer. * Output of the Program * Note: instead of dtptr >day (*dtptr).day could be also used.

Accessing Structure Members Example- Page 419 * Output of the Program *

Page 420 In the programs using structures, "struct tag variable;" statement is used every time to define a new variable with this type. In order to avoid typing struct tag variable every time, C programming language allows programmers to define a synonym (or alias) to the "struct tag", so programmer don't need to type it every time. The keyword typedef creates synonyms (or aliases) for data types. Names for structure types are often defined with typedef to create shorter type names.

Page 420 Let s revisit the card structure example struct card {/* card structure definition */ char *face; /* define pointer face */ char *suit; /* define pointer suit */ }; /* end structure card */ // Now define structure Synonym usually the capital letter of the struct. tag typedef struct card Card; // Card is now Synonym struct card // Now on, we can use the structure Synonym to define a variable Card acard; // same as struct card acard; Card *cardptr; // same as struct card *cardptr; C programmers often use typedef to define a structure type, so a structure tag is not required. Synonym is then used to declare a variable with this type. As an example, the above structure definition can be done without tag. typedef struct { //Defining Structure without tag char *face; char *suit; } Card; /* Card is the Synonym to this structure */ Card acard; // Defines the type via the synonym

Swapping Structure Variables Out of Book Below program demonstrates copying a structure variable to another and usage of typedef command. * Output of the Program * Note: Copying a structure variable to another structure variable of the same type is very simple.

Page 420 It is possible to pass a structure or structures to functions in two ways. Structures may be passed to functions by passing individual structure members one by one (Call-by-Value). In this method, structure members are passed by value, therefore, the members of a caller s structure cannot be modified by the called function. It is also possible to pass the entire structure or by passing a pointer to the structure (Call-by-Reference). In this method, structure members are passed by reference (like memory address) and the caller's structure can be modified by the function (as like passing an array with reference). Passing structure by reference is a lot more efficient than passing structures by value. Passing a structure variable to a function is very similar to passing an array to a function.

More on Using Structures with Functions Page 420 Using structures/passing to a function and getting a feedback/return from a function can be used for may purposes. Because, call-by-reference is more efficient, it will under consideration in this slide. Segment of program given below demonstrates the usability of functions for different ways. struct card {/* card structure definition */ char *face; /* define pointer face */ char *suit; /* define pointer suit */ }; /* end structure card */ typedef struct card Card; // Card is now Synonym struct card // Function prototypes This are also the first lines of the functions - void function1( struct card a, int size); int function2( Card a, Card b, int size); char *function3( Card a ); struct card function 4 ( struct card a, int x, int y); Under main function, below lines shows how we can pass the structures. Let s assume person_a, person_b, and person_c are defined as structure variable of type card and x, y, xx, and yy are integer type of variables. function1(person_a); x = function2(person_a, person_b, y); printf( %s, function3(person_b); person_c = function4(person_a, xx, yy);

Structures with Functions Example- Out of Book Below program prints a given date in EU standard (dd/mm/yyyy) and US standard (mm/dd/yyyy). Each task is accomplished by separate functions. * Output of the Program *

Structures with Functions Example- Out of Book Below program demonstrates the usage of function to compare two dates. Function receives two date structure variables and returns the earlier date. * Output of the Program *

Arrays of Structures Page 421 In the previous example, we have used a structure variables to keep track of the employee card information for only two workers. We have defined the structure variables as; struct employee person_a; struct employee person_b; If we have too many employees then we can define a structure array variable by which we can deal with as many as employee records/information. It is very similar to array declaration; struct employee person[100]; This will create person[0],, person[99] and each one of them has members defined as person[i].name person[i].last person[i].age person[i].salary where 0 i < 100. (100 variables are defined).

Initialization of Arrays of Structures Page 423 Let s now consider the example d[3] array of structures to keep track of three dates employees information. struct date d[3]; //members are dd mm yyyy Members of the d[0], d[1],and d[2] can be read from keyboard or assigned within the program using the following. operator d[i].day d[i].month d[i].year where 0 i < 3. Also the members can be initialized at the time of declaration typedef struct date Date; /* Emp is synonym*/ struct date d[3]={{11,5,2004}}; Date d[3]={{11,5,2004}, {21,6,2004},{11,6,2012}}; /* inner braces are optional below line does the same */ Date d[3]={11,5,2004,21,6,2004,11,6,2012}; Date d[3]={{11,5,2004}, {21,6,2004}, {11,6,2012}}; Date d[3]={[2]= {11,6,2012}};

Structures with Functions Example- Out of Book Below program demonstrates the usage of array of structures to keep track of the five student exam results. Calculating avg. then printing them * Output of the Program *

Pointers and Arrays Example- Out of Book Array of Structures and pointers are strongly related. An array of structure can be pointed by a pointer and can be processed through this pointer. * Output of the Program *

Last Comment on Pointers and Arrays Out of Book In order to understand how actually pointers and arrays are related, we should look at how an array of structure is stored in the memory. Below an array of structure named months with type of month is defined. It holds the 3 Letters and Number of days in this month.** Right figure shows the array in the memory. struct month { //Defining Structure int numberofdays; char name[3]; }; struct month months[12] ={ {31,"Jan"}, {28,"Feb"}, {31,"Mar"},{30,"Apr"},{31,"May"},{30,"Jun"}, {31,"Jul"},{30,"Aug"},{30,"Sep"},{31,"Oct"}, {30,"Nov"},{31,"Dec"}}; //Pointing the forth element of the array of structure struct month *mptr = months[3]; mptr We can make mptr point next element by mptr++

Page 423 A union is a derived data type like a structure with members that share the same storage space. For different situations in a program, some variables may not be relevant, but other variables are so a union shares the space instead of wasting storage on variables that are not being used. Definition and usage of unions are similar to structure typedef union shape{ //Defining Union double radius; //Needs a size of 6 bytes double length; //Needs a size of 6 bytes double width; //Needs a size of 6 bytes }; // Total space is 6 bytes Note: Advantage of using union instead of structure. Size of the union unlike structure is adjusted according to the structure variable that requires the maximum usage from the members of the union. This helps on saving storage on the memory when dealing with large amount of data.

10.11 Enumeration Constants Page 438 As we have learned before, we can define constants in our program by using #define SIZE 10. User-defined data can be also defined by using enumeration. Each enumeration starts with enum statement. By default, enumeration starts with 0, unless specified otherwise. this creates enumeration constants with type of months with values from 0 to 11. (same like #define JAN 0.) enum statement allows user to define the starting value as below; Note: Enumeration constants doesn t take any storage on the memory and they are constant throughout the program.

Enumeration Example- Page 439 * Output of the Program *

Page 439 NOTE: Add a slide on nested structures See C programlama Dili Page 268 Unions are presented as separate chapter in C Programming Language 3 rd Edition See the referenced text and add some clear examples on the usage of unions.