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

Similar documents
OBJECT ORIENTED PROGRAMMING USING C++

C Structures, Unions, Bit Manipulations, and Enumerations

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

Chapter 8 STRUCTURES IN C

BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$12$

Programming for Engineers Structures, Unions

Chapter 6 - Pointers

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

Pointers. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then

Pointers and Strings Prentice Hall, Inc. All rights reserved.

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

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

C Pointers Pearson Education, Inc. All rights reserved.

CS Programming I: Arrays

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

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

Programming for Engineers Pointers

Fundamental of Programming (C)

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

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

Chapter 10 C Structures, Unions, Bit Manipulations

Definition: Data Type A data type is a collection of values and the definition of one or more operations on those values.

CSE 230 Intermediate Programming in C and C++

Dynamic Memory Allocation

Undergraduate Admission File

Types, Operators and Expressions

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings

Types, Operators and Expressions

File Handling in C. EECS 2031 Fall October 27, 2014

DATE OF BIRTH SORTING (DBSORT)

Data Structures and Algorithms (DSA) Course 4. Iulian Năstac

Data Types. 9. Types. a collection of values and the definition of one or more operations that can be performed on those values

A flow chart is a graphical or symbolic representation of a process.

High Performance Computing

Arrays and Pointers (part 2) Be extra careful with pointers!

AIMMS Function Reference - Date Time Related Identifiers

Arrays and Pointers (part 2) Be extra careful with pointers!

14. Other Data Types. Compound Data Types: Defined data types (typedef) Unions typedef existing_type new_type_name ;

CSE 230 Intermediate Programming in C and C++

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Programación de Computadores. Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana

Lecture 14. Dynamic Memory Allocation

CIMA Asia. Interactive Timetable Live Online

Computers Programming Course 6. Iulian Năstac

Syntax and Variables

Computers Programming Course 5. Iulian Năstac

Recursion Enums. Basics of Programming 1. Department of Networked Systems and Services G. Horváth, A.B. Nagy, Z. Zsóka, P. Fiala, A.

Lecture 05 POINTERS 1

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

Grade 4 Mathematics Pacing Guide

Darshan Institute of Engineering & Technology for Diploma Studies Unit 5

MCA Semester 1. MC0061 Computer Programming C Language 4 Credits Assignment: Set 1 (40 Marks)

Data Types H&K Chapter 7. Instructor - Andrew S. O Fallon CptS 121 (October 17, 2018) Washington State University

CIMA Asia. Interactive Timetable Live Online

IV Unit Second Part STRUCTURES

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

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

STRUCTURES & FILE IO

Relationship between Pointers and Arrays

Review Questions II KEY

OBJECT ORIENTED PROGRAMMING

Content. In this chapter, you will learn:

Freedom of Information Act 2000 reference number RFI

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

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

Beginning C Programming for Engineers

1 Pointer Concepts. 1.1 Pointer Examples

MYcsvtu Notes LECTURE 34. POINTERS

INFORMATION TECHNOLOGY SPREADSHEETS. Part 1

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Presented By : Gaurav Juneja

Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso

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

Why arrays? To group distinct variables of the same type under a single name.

REPORT ON TELECOMMUNICATIONS SERVICE QUALITY WINDSTREAM FLORIDA, INC.

... Lecture 12. Pointers

DEPARTMENT OF MATHS, MJ COLLEGE

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Data Structures Unit 02

C++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved.

CS1100 Introduction to Programming

Scientific Programming in C X. More features & Fortran interface

Arrays. What if you have a 1000 line file? Arrays

Functions. Introduction :

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

Lecture 10: Boolean Expressions

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Pointer in C SHARDA UNIVERSITY. Presented By: Pushpendra K. Rajput Assistant Professor

Bit Manipulation in C

Arithmetic Operators. Portability: Printing Numbers

13. Data Structures. struct type_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3;..

NMOSE GPCD CALCULATOR

AGENDA Binary Operations CS 3330 Samira Khan

C Pointers. CS 2060 Week 6. Prof. Jonathan Ventura

Tutorial 8 (Array I)

CS 61C: Great Ideas in Computer Architecture Introduction to C

History. used in early Mac development notable systems in Pascal Skype TeX embedded systems

Transcription:

Introduction Structures, Unions, Bit Manipulations, and Enumerations In C, we can create our own data types If programmers do a good job of this, the end user does not even have to know what is in the data type struct is used to describe a new data type. typedef is used to associate a name with it. int, double and char are types of variables. With struct you can create your own. It is a new way to extend the C programming language. CS25 Peter Lo 24 CS25 Peter Lo 24 2 Structure Collections of related variables (aggregates) under one name Can contain variables of different data types Commonly used to define records to be stored in files Combined with pointers, can create linked lists, stacks, queues, and trees Structure Definitions Example struct card { char *face; char *suit; }; struct introduces the definition for structure card card is the structure name and is used to declare variables of the structure type card contains two members of type char * These members are face and suit CS25 Peter Lo 24 3 CS25 Peter Lo 24 4

Structure Definitions struct information Astruct cannot contain an instance of itself Can contain a member that is a pointer to the same structure type A structure definition does not reserve space in memory Instead creates a new data type used to declare structure variables Structure Declaration Declarations Declared like other variables: card onecard, deck[ 52 ], *cptr; Can use a comma separated list: struct card { char *face; char *suit; } onecard, deck[ 52 ], *cptr; CS25 Peter Lo 24 5 CS25 Peter Lo 24 6 Accessing Members of Structures Example 8A Accessing structure members Dot operator (.) used with structure variables card mycard; printf( "%s", mycard.suit ); Arrow operator (->) used with pointers to structure variables card *mycardptr = &mycard; printf( "%s", mycardptr->suit ); mycardptr->suit is equivalent to ( *mycardptr ).suit CS25 Peter Lo 24 7 /* 8A: Using the structure member and structure pointer operators */ #include <stdio.h> #include <conio.h> struct card { char *face; char *suit; ; int main() structcard a; struct card *aptr ; a.face = "Ace"; a.suit = "Spades"; aptr = &a; printf( "%s%s%s\n%s%s%s\n%s%s%s\n", a.face, " of ", a.suit, aptr->face, " of ", aptr->suit, ( *aptr ).face, " of ", ( *aptr ).suit ); getch(); return ; CS25 Peter Lo 24 8

Output Result Using Structures With Functions Passing structures to functions Pass entire structure Or, pass individual members Both pass call by value To pass structures call-by-reference Pass its address Pass reference to it To pass arrays call-by-value Create a structure with the array as a member Pass the structure CS25 Peter Lo 24 9 CS25 Peter Lo 24 typedef Example typedef allows us to associate a name with a structure (or other data type). Creates synonyms (aliases) for previously defined data types Use typedef to create shorter type names Example: typedef struct Card *CardPtr; Defines a new type namecardptr as a synonym for typestruct Card * typedef does not create a new data type Only creates an alias typedef struct line { int x, y; int x2, y2; } LINE; int main() { LINE line; } line is now a structure of line type This is what was happening with all that FILE * stuff CS25 Peter Lo 24 CS25 Peter Lo 24 2

Example 8B Example 8B (cont ) /*8B The card shuffling and dealing program using structures */ #include<stdio.h> #include<stdlib.h> #include <time.h> #include<conio.h> struct card { const char *face; const char *suit; ; typedef struct card Card; void filldeck ( Card * const, const char *[], const char *[] ); void shuffle( Card * const ); void deal( const Card * const ); CS25 Peter Lo 24 3 int main() Card deck[ 52 ]; const char *face[] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}; const char *suit[] = { "Hearts", "Diamonds", "Clubs", "Spades"}; srand( time( NULL ) ); filldeck ( deck, face, suit ); shuffle( deck ); deal( deck ); return ; CS25 Peter Lo 24 4 Example 8B (cont ) Example 8B (cont ) void filldeck ( Card * const wdeck, const char * wface[], const char * wsuit[] ) int i; for ( i = ; i <= 5; i++ ) { wdeck[ i ].face = wface[ i % 3 ]; wdeck[ i ].suit = wsuit[ i / 3 ]; void shuffle( Card * constwdeck ) int i, j; Card temp; for ( i = ; i <= 5; i++ ) { j = rand() % 52; temp = wdeck [ i ]; wdeck[ i ] = wdeck [ j ]; wdeck[ j ] = temp; CS25 Peter Lo 24 5 void deal( const Card * const wdeck ) int i; for ( i = ; i <= 5; i++ ) printf( "%5s of %-8s%c", wdeck [ i ].face, wdeck [ i ].suit, ( i + ) % 2? '\t' : '\n' ); CS25 Peter Lo 24 6

Output Result Unions Memory that contains a variety of objects over time Only contains one data member at a time Members of a union share space Conserves storage Only the last data member defined can be accessed CS25 Peter Lo 24 7 CS25 Peter Lo 24 8 union declarations Valid union Operations union declarations Same as struct union Number { int x; float y; }; union Number value; Valid union operations Assignment to union of same type: = Taking address: & Accessing union members:. Accessing members using pointers: -> CS25 Peter Lo 24 9 CS25 Peter Lo 24 2

Example 8C Output Result /* 8 C: An example of a union */ #include<stdio.h> #include<conio.h> union number { int x; double y; ; int main() { union number value; value.x = ; printf( "%s\n%s\n%s%d\n%s%f\n\n", "Put a value in the integer member", "and print both members.", "int: ", value.x, "double:\n", value.y ); value.y =.; printf( "%s\n%s\n%s%d\n%s%f\n", "Put a value in the floating member", "and print both members.", "int: ", value.x, "double:\n", value.y ); getch (); return ; CS25 Peter Lo 24 2 CS25 Peter Lo 24 22 Bitwise Operators Bitwise Operators All data represented internally as sequences of bits Each bit can be either or Sequence of 8 bits forms a byte Operator & Name bitwise AND bitwise OR Description The bits in the result are set to if the corresponding bits in the two operands are both. The bits in the result are set to if at least one of the corresponding bits in the two operands is. x y AND x&y OR x y XOR x^y x Complement ~x ^ << >> ~ bitwise exclusive OR left shift right shift One s complement The bits in the result are set to if exactly one of the corresponding bits in the two operands is. Shifts the bits of the first operand left by the number of bits specified by the second operand; fill from right with bits. Shifts the bits of the first operand right by the number of bits specified by the second operand; the method of filling from the left is machine dependent. All bits are set to and all bits are set to. CS25 Peter Lo 24 23 CS25 Peter Lo 24 24

Example 8D Example 8D (cont ) /* 8D: Using the bitwise AND, bitwise inclusive OR, bitwise exclusive OR and bitwise complement operators */ #include <stdio.h> #include <conio.h> void displaybits( unsigned ); int main() unsigned number, number2, mask,setbits; number = 65535; mask = ; printf( "The result of combining the following\n" ); displaybits( number ); displaybits( mask ); printf( "using the bitwise AND operator & is\n" ); displaybits( number & mask ); number = 2845; printf( "\ntheone's complement of\n" ); CS25 Peter Lo 24 25 displaybits( number ); printf( "is\n" ); number = 5; setbits= 24; printf( "\nthe result of combining the following\n" ); displaybits( number ); displaybits( setbits ); printf( "using the bitwise inclusive OR operator is\n" ); displaybits( number setbits); number = 39; number2 = 99; printf( "\nthe result of combining the following\n" ); displaybits( number ); displaybits( number2 ); printf( "using the bitwise exclusive OR operator ^ is\n" ); displaybits( number ^ number2 ); displaybits( ~number ); getch(); return ; CS25 Peter Lo 24 26 Example 8D (cont ) Output Result void displaybits( unsigned value ) { unsigned c, displaymask = << 3; printf( "%7u = ", value ); for ( c = ; c <= 32; c++ ) { putchar( value & displaymask? '' : '' ); value <<= ; if ( c % 8 == ) putchar( ' ' ); putchar( '\n' ); CS25 Peter Lo 24 27 CS25 Peter Lo 24 28

Enumeration Constants Enumeration Set of integer constants represented by identifiers Enumeration constants are like symbolic constants whose values are automatically set Values start at and are incremented by Values can be set explicitly with = Need unique constant names Enumeration Constants Example: enum Months { JAN =, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; Creates a new type enummonths in which the identifiers are set to the integers to 2 Enumeration variables can only assume their enumeration constant values (not the integer representations) CS25 Peter Lo 24 29 CS25 Peter Lo 24 3 Example 8F Output Result /* 8F Using an enumeration type */ #include <stdio.h> #include <conio.h> enummonths { JAN =, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }; int main() enummonths month; const char *monthname[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; for ( month = JAN; month <= DEC; month++ ) printf( "%2d%s\n", month, monthname[ month ] ); getch(); return ; CS25 Peter Lo 24 3 CS25 Peter Lo 24 32