Arrays III and Enumerated Types

Similar documents
Repetition Structures II

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

AIMMS Function Reference - Date Time Related Identifiers

Selection Structures II

INFORMATION TECHNOLOGY SPREADSHEETS. Part 1

Scientific Programming in C X. More features & Fortran interface

Enumerated Types. Mr. Dave Clausen La Cañada High School

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

Programming for Engineers Structures, Unions

High Performance Computing

Lecture 17. Strings II. CptS 121 Summer 2016 Armen Abnousi

Lecture 14. Arrays II. Selection Sort & Parallel Arrays. CptS 121 Summer 2016 Armen Abnousi

CMIS 102 Hands-On Lab

Lecture 5. Functions II. Functions with Arguments. CptS 121 Summer 2016 Armen Abnousi

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

Conditional Formatting

Lecture Notes: ESC 101

Daily Math Week 10 ( ) Mon. October 21, 2013 Tues. October 22, 2013 Wed. October 23, 2013 Thurs. October 24, 2013 Fri.

Lecture 3. The syntax for accessing a struct member is

Private Swimming Lessons

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

(3-2) Basics of a Stack. Instructor - Andrew S. O Fallon CptS 122 (January 26, 2018) Washington State University

(6-1) Basics of a Queue. Instructor - Andrew S. O Fallon CptS 122 (September 26, 2018) Washington State University

Programming Language B

CS349/SE382 A1 C Programming Tutorial

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

Computer Science & Engineering 150A Problem Solving Using Computers

Package RcppBDT. August 29, 2016

(2-1) Data Structures & The Basics of a Linked List I. Instructor - Andrew S. O Fallon CptS 122 (August 27, 2018) Washington State University

Schedule/BACnet Schedule

Project 1 System Calls

(9-1) Arrays IV Parallel and H&K Chapter 7. Instructor - Andrew S. O Fallon CptS 121 (March 5, 2018) Washington State University

Dynamic Data Structures (II)

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

Syntax and Variables

CIMA Certificate BA Interactive Timetable

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

Package taskscheduler

What if Analysis, Charting, and Working with Large Worksheets. Chapter 3

Fundamental of Programming (C)

MONITORING REPORT ON THE WEBSITE OF THE STATISTICAL SERVICE OF CYPRUS DECEMBER The report is issued by the.

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

Introduction to Computing Lecture 05: Selection (continued)

(8-1) Arrays I H&K Chapter 7. Instructor - Andrew S. O Fallon CptS 121 (October 8, 2018) Washington State University

PASCAL. PASCAL, like BASIC, is a computer language. However, PASCAL, unlike BASIC, is a Blocked Structured Language (BASIC is known as unstructured).

Payflow Implementer's Guide FAQs

76 days Wed 8/24/16 Wed 12/7/16 Daniel Wang,Shreyas Makde,Madhavi Potluri,Roua 2 Requirements analysis 11 days Wed 8/24/16 Wed 9/7/16

Object-Oriented Principles and Practice / C++

Chapter 7: Structuring the Data. Lecture7 1

C# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

CA341 - Comparative Programming Languages

12 CREATING NEW TYPES

EECS402 Lecture 24. Something New (Sort Of) Intro To Function Pointers

How It All Stacks Up - or - Bar Charts with Plotly. ISC1057 Janet Peterson and John Burkardt Computational Thinking Fall Semester 2016

C# Types. Industrial Programming. Value Types. Signed and Unsigned. Lecture 3: C# Fundamentals

Industrial Programming

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions

Classification s of Data Structures

DUTCH BENCHMARK The 2017 Edition

A class is a user-defined type. It is composed of built-in types, other user-defined types and

Other conditional and loop constructs. Fundamentals of Computer Science Keith Vertanen

Java Programming Language Mr.Rungrote Phonkam

Daily Math Week 8 ( ) Mon. October 7, 2013 Tues. October 8, 2013 Wed. October 9, 2013 Thurs. October 10, 2013 Fri.

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

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

OBJECT ORIENTED PROGRAMMING USING C++

Computer Programming: C++

C Structures, Unions, Bit Manipulations, and Enumerations

Pointer Arithmetic and Lexical Scoping. CS449 Spring 2016

BLM2031 Structured Programming. Zeyneb KURT

Darshan Institute of Engineering & Technology for Diploma Studies Unit 5

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

(3-3) File Processing with Functions. Instructor - Andrew S. O Fallon CptS 121 (January 26, 2018) Washington State University

Lesson 7. Reading and Writing a.k.a. Input and Output

I I. I I Wed 28-Jan-I WW1 - External Data I. EPF 29.5 Water Results. Consent of copyright owner required for any other use.

GEOMETRY (TENTATIVE SCHEDULE) WEEK 1. Abbreviations: LT = Learning Target, Std. = Standard GR = Geometry Review Worksheet (Mixed Math Review)

Scheduling. Scheduling Tasks At Creation Time CHAPTER

Total Market Demand Wed Jul 26 Thu Jul 27 Fri Jul 28 Sat Jul 29 Sun Jul 30 Mon Jul 31 Tue Aug 01

CS Programming I: Arrays

DEPARTMENT OF ACADEMIC UPGRADING

software.sci.utah.edu (Select Visitors)

Dean Harrison IBM. Date of presentation (03/11/2015) Session NE. WAPL A Sheepdog in the Pen

Structures and Pointers

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

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

This is part of the book COMPUTER PROGRAMMING THE C LANGUAGE. by Adriana ALBU. Conspress Publisher, Bucureşti, România, 2013 ISBN:

Types, Operators and Expressions

Lecture 14. Dynamic Memory Allocation

Introduction. A4 Elem of Style. Introduction

ICT PROFESSIONAL MICROSOFT OFFICE SCHEDULE MIDRAND

Operator overloading: extra examples

Ohad Barzilay and Oranit Dror

(7-2) Modular Programming II H&K Chapter 6. Instructor - Andrew S. O Fallon CptS 121 (February 22, 2019) Washington State University

CSCE 314 Programming Languages

WoTRS Master Calendar

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

More Binary Search Trees AVL Trees. CS300 Data Structures (Fall 2013)

A Hybrid Constraint Programming Approach to Nurse Rostering Problem

BHARATI VIDYAPEETH`S INSTITUTE OF MANAGEMENT STUDIES AND RESEARCH NAVI MUMBAI ACADEMIC CALENDER JUNE MAY 2017

Transcription:

Lecture 15 Arrays III and Enumerated Types Multidimensional Arrays & enums CptS 121 Summer 2016 Armen Abnousi

Multidimensional Arrays So far we have worked with arrays with one dimension. Single dimensional arrays can logically be thought of as vectors. We can also declare and use multidimensional arrays Multidimensional arrays can be logically though of as 2D tables, 3D tables (cubes), A multidimensional array in memory is just an array of arrays. Are usefule when you need to store a table. e.g. tic-tactoe board, matrices, etc.

Multidimensional Arrays - Declaration Declare them as: type name[size of d1][size of d2][size of d3] char tictactao[3][3] If we are initializing during declaration, we can omit the size of the first dimension: (only the first) char tictactoe[ ][3] =. int my3darray[ ][15][200] =. 0 0 1 2 tictactoe[0][0] 1 2 tictactoe[0][2] tictactoe[2][1]

Multidimensional Arrays - Initialization char tictactao[3][3] =,,,,,,,, ; int mytable[2][3] = 1, 3, 4, 2, 5, 7 ; int mytable[ ][3] = 1, 3, 4, 2, 5, 7 ; Even when initializing during the declaration the 2 nd, 3 rd, and higher dimension sizes should be given! invalid: int mytable[][] = 1, 3, 4, 2, 5, 7 ; This is true, when using multidimensional arrays as function parameters: only the first dimension size can be eliminated from the header. int myfunction(int mythreedimarray[][2][3]);

Traversing Over Multidimensional Arrays We can use nested loops to traverse over these arrays Each loop will iterate over one dimension of the array. int table[2][3] = 3, 5, 7, 2, 4, 6 ; for (i = 0; i < 2; i++) for (j = 0; j < 3; j++) sum += table[i][j];

Example Matrix Summation Assuming we show each matrix as a 2D array, write a program that performs addition for two 2*3 matrices. a 1 a 2 a 3 a 4 a 5 a + b 1 b 2 b 3 = a 1 + b 1 a 2 + b 2 a 3 + b 3 6 b 4 b 5 b 6 a 4 + b 4 a 5 + b 5 a 6 + b 6

Example Matrix Summation #define NUM_COLUMNS 3 int addmatrices(double a[][num_columns], int arows, double b[][num_columns], int brows, int result[][num_columns]) int success = 1, i, j; if ( arows!= brows ) printf( cannot add two matrices! ); success = 0; else for ( i = 0; i < arows; i++ ) for ( j = 0; j < NUM_COLUMNS; j++ ) results[i][j] = a[i][j] + b[i][j]; return success; Writing all dimension sizes except optionally the first one is mandatory

Enumerated Types (enum) Sometimes we want to define our own data types rather than using int, double, etc. Enumerated types are data types we can create (there are other ways to define new data types too) We are working with week days. One way is to represent each day as an integer Monday = 1, Tuesday = 2 More convenient way is to define a new data type weekday_t

Enumerated Types typedef enum monday, tuesday, wednesday, thursday, friday weekday_t; Valid values for this data type Name of the type we are creating Now weekday_t is a data type and you can use it to declare variables: weekday_t today = monday; (int day = 0;)

Enumerated Types typedef enum monday, tuesday, wednesday, thursday, friday weekday_t; A new data type called weekday_t is defined. Valid data values for a variable of type weekday_t are monday, tuesday, wednesday, thursday, and friday *Behind the scene monday gets int value 0, tuesday gets 3, wednesday 4, and so on.

Enumerated Types We can say: weekday_t today = monday; weekday_t tomorrow = today + 1; We can iterate over an enum using loops: weekday_t day; for (day = monday; day <= friday; day++) We can also convert from enums to int or vice versa. int daynumber = (int) today; weekday_t today = (weekday_t) 3; We can use enums as array indices: customerscount[ monday ] = 10; We can use them in switch-case operations

typedef enum false, true Bool; Common/Useful enums typedef enum Month; jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec *By writing jan = 1 in Month enum, the integer association to month identifiers start from 1 rather than 0.

Printing enums Enums can be used in switch statements (useful for printing them!) void printweekday(weekday_t day) switch (day) case monday: printf( Monday ); Note: C does not provide specific functions/placeholders for writing/reading enum data.

Enum - notes Valid values for enums are called enumeration constants. monday, tuesday, in our example are enumerations constants Enumeration constants must be identifiers (names), they cannot be constant numbers or string literals. One identifier cannot be used in more than one enum definition.

Example Super Market Sales A super market keeps records of its amount of daily sales in a week for each of the categories: Cleaning products, Drinks, Patio and garden, Books Pharmacy (assume there are no row/column headers in the records file. Here we include headers for illustration) Write a program that prints the highest selling category for each day of the week.

Example Super Market Sales Solution: enums #define CATEGORIES_COUNT 5 #define DAYS_COUNT 7 typedef enum mon, tue, wed, thu, fri, sat, sun days_t; typedef enum cleaning, drinks, garden, books, pharmacy category_t;

Example Super Market Sales Solution: Reading the records void readrecords(double sales[days_count][categories_count]) If the file opened successfully category_t category = cleaning; day_t day = mon; FILE* infile = fopen( supermarket.txt, r ); if ( infile!= NULL ) else for ( category = cleaning; category <= pharmacy; category++) for (day = mon; day <= sun; day ++) printf( file cannot be opened!\n ); fscanf(infile, %lf, &sales[day][category]); For each category For each day Scan the amount of sale You might want to add a status check for the returned value of fscanf

Example Super Market Sales Solution: Finding the daily max sales void findmaxsales(double sales[days_count][categories_count]) category_t category = cleaning, dailymaxcategory = cleaning; day_t day = mon; double dailymaxamount = 0.0; for (day = mon; day <= sun; day++) dailymaxamount = 0; for (category = cleaning; category <= pharmacy; category++) if ( sales[day][category] > dailymaxamount ) dailymaxcategory = category; dailymaxamount = sales[day][category]; printf( for day %d, highest selling category was %d, with sale amount of %f\n, (int) day, (int) dailymaxcategory, dailymaxamount);

References J.R. Hanly & E.B. Koffman, Problem Solving and Program Design in C (8thed.), Pearson, 2016 Andy O Fallon s lecture notes for CptS121 (http://eecs.wsu.edu/~aofallon/cpts121)