Unit 6 Data Types and Arrays. Key Concepts Explicit and automatic conversion ASCII Enumerated types Function parameters Arrays Loops and arrays Passing.

Slides:



Advertisements
Similar presentations
Topic Reviews For Unit ET156 – Introduction to C Programming Topic Reviews For Unit
Advertisements

Numeric Types & Ranges. ASCII Integral Type Numerical Inaccuracies Representational error – Round-off error – Caused by coding a real number as a finite.
Introduction to C Programming
One Dimensional Arrays
Week 8 Arrays Part 2 String & Pointer
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 8: Arrays Problem Solving & Program Design in C Sixth Edition.
Sizes of simple data types sizeof(char) = 1 size(short) = 2 sizeof(int) = 4 size(long) = 8 sizeof(char) = 1 size(short) = 2 sizeof(int) = 2 size(long)
Chapter 7 Simple Date Types Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. TA: 鄭筱親 陳昱豪.
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.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
Scope and Casting. Scope Region of the program where a particular name can be referenced Formal parameters and local variables –can be accessed from within.
Lab 10 rRepresentation And Conversion of Numeric Types l Difference between Numeric Types l Automatic conversion of Data types l Explicit Conversion of.
1 CSC 1401 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
1 CS 201 Array Debzani Deb. 2 Having trouble linking math.h? Link with the following option gcc –lm –o test test.o.
Instructor: Sanchita Mal-Sarkar Course: CIS 265
Lab 11 rArrays rExercises Note: Read the whole Chapter 8.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Representation and Conversion of Numeric Types 4 We have seen multiple data types that C provides for numbers: int and double 4 What differences are there.
Chapter 7 Simple Data Types and Function Calls Alkar / Demirer.
Chapter 7 Simple Date Types Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
The University of Texas – Pan American
 2006 Pearson Education, Inc. All rights reserved Arrays.
chap8 Chapter 8 Arrays (Hanly) chap8 2 Data Structure Simple data types use a simple memory to store a variable. Data Structure: a.
A First Book of ANSI C Fourth Edition
chap7 Chapter 7 Simple Data Types chap7 2 Objectives No programming language can predefine all the data types that a programmer may.
Chapter 7 Simple Date Types J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
A.Abhari CPS1251 Multidimensional Arrays Multidimensional array is the array with two or more dimensions. For example: char box [3] [3] defines a two-dimensional.
Chapter 8 Arrays and Strings
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Chapter 8 Arrays Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University of.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman CP 202 Chapter
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
CISC105 – General Computer Science Class 9 – 07/03/2006.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
CIS-165 C++ Programming I CIS-165 C++ Programming I Bergen Community College Prof. Faisal Aljamal.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Chapter 8 Arrays Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
Programming Logic and Design Fourth Edition, Comprehensive Chapter 8 Arrays.
Arrays Why we need data structure? Simple data types use a single memory cell to store a variable. Sometimes (for example scores of a class) it is more.
Chapter 8 Arrays Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. TA: 鄭筱親 陳昱豪.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Simple Data Types Chapter Constants Revisited t Three reasons to use constants –Constant is recognizable –Compiler prevents changes in value.
Simple Data Types Chapter Constants Revisited t Three reasons to use constants –Constant is recognizable –Compiler prevents changes in value.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin.
Problem Solving and Program Design in C Chap. 7 Arrays Chow-Sing Lin.
Chapter INTRODUCTION Data Types and Arithmetic Calculations.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Objectives You should be able to describe: One-Dimensional Arrays
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Arrays and Records.
Simple Data Types and Function Calls
CNG 140 C Programming (Lecture set 8)
Chapter 8: Arrays Problem Solving and Program Design in C 5th Edition
Chapter 8 Arrays Dr. Jiung-yao Huang Dept. Comm. Eng.
Chapter 7 Simple Date Types Dr. Jiung-yao Huang Dept. Comm. Eng.
Chapter 8: Arrays Problem Solving and Program Design in C 5th Edition
Presentation transcript:

Unit 6 Data Types and Arrays

Key Concepts Explicit and automatic conversion ASCII Enumerated types Function parameters Arrays Loops and arrays Passing array elements to a function Array parameters Returning an array Stacks Searching an array Sorting an array Multidimensional arrays

Figure 7.1 Internal Formats of Type int and Type double

Figure 7.2 Program to Print Implementation-Specific Ranges for Positive Numeric Data

Integer Types in C Table 7.1

Floating-Point Types in C Table 7.2

Numerical Inaccuracies Representational error – Round-off error – Caused by coding a real number as a finite number of digits – Magnified through repeated computations Cancellation error – Caused by adding a very large number and a very small number Arithmetic underflow – Caused by multiplying very small numbers Arithmetic overflow – Caused by multiplying very large numbers

Implicit Conversion Assume variables: int k=5, m=4, n; double x=1.5, y=2.1, z; Operands of different types – Narrow type converted to wider type before calculation k + x /*Evaluates to 6.5 */ Expression evaluated before assignment z = k / m; /*Evaluates to 1, assigns 1.0 */ n = x * y; /* Evaluates to 3.5, assigns 3. */

Explicit Conversion Convert data type using a cast int n1, d1; scan_fraction(&n1, &dl); /*integer division performed. n1=2, d1=4, result=0*/ frac = n1 / d1; /*Use cast to force floating point division. Result = 1.5*/ frac = (double)n1 / (double)n2;

ASCII Characters ASCII CodesRepresent 32 through 126Printable characters 48 through through 90A-Z 97 through 122a-z 0 through 31 and 127Non-printable characters

Figure 7.3 Program to Print Part of the Collating Sequence

Enumerated Types Used to improve program readability typedef enum {entertainment, rent utilities, food, clothing } expense_t; rent is an enumeration constant with the value 1 Add typedef declarations immediately after preprocessor directives.

Figure 7.4 Enumerated Type for Budget Expenses

Figure 7.4 Enumerated Type for Budget Expenses (cont’d)

1-15 Figure 7.4 Enumerated Type for Budget Expenses (cont’d)

Figure 7.5 Accumulating Weekday Hours Worked continued

Figure 7.5 Accumulating Weekday Hours Worked (cont’d)

Figure 7.6 Six Roots for the Equation f(x) = 0

Figure 7.7 Using a Function Parameter

Figure 7.8 Change of Sign Implies an Odd Number of Roots

Figure 7.9 Three Possibilities That Arise When the Interval [xleft, xright] Is Bisected

Figure 7.10 Finding a Function Root Using the Bisection Method

Figure 7.10 Finding a Function Root Using the Bisection Method (cont’d)

Figure 7.11 Sample Run of Bisection Program with Trace Code Included

Figure 8.1 The Eight Elements of Array x

Parallel Arrays #define NUM_STUDENTS 50 int id[NUM_STUDENTS]; double gpa[NUM_STUDENTS];

Array of Characters #define NUM_QUEST 10 char answer[NUM_QUEST]; answer[0] = 'T'; answer[1] = 'F'; answer[2] = 'F'

Accessing an Array with an Enumerated Constant #define NUM_CLASS_DAYS 5 typedef enum {monday, tuesday, wednesday, thursday, friday} class_days_t; int score[NUM_CLASS_DAYS]; score[monday] = 9; score[Tuesday] = 7;

Figure 8.2 Arrays answer and score

Array Initialization When initializing array in its declaration, omit the size. int prime_lt_100[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};

Processing an Array Using a Loop Use a counter-controlled loop #define SIZE 11 int square[SIZE], i; for (i= 0; i < SIZE; ++i) square[i] = i * i;

Figure 8.3 Program to Print a Table of Differences

Figure 8.3 Program to Print a Table of Differences (cont’d)

Array Elements as Function Arguments Array elements can be used as input or output arguments. Consider the function with the prototype: void do_it (double arg_1, double *arg2_p, double *arg3_p); Pass array x elements as arguments: do_it(x[0], &x[1], &x[2]); input argument output arguments

Figure 8.4 Data Area for Calling Module and Function do_it

Figure 8.8 Diagram of a Function That Computes an Array Result

Arrays as Parameters Passing an array as a parameter passes the pointer to the array, not a copy. – Function can modify the array. Function prototype that accepts an array: void fill_array (int list[], int n, int, in_value); /* Clearer */ or void fill_array (int *list, int n, int, in_value);

Figure 8.5 Function fill_array

Passing an Array Argument Because an array argument refers to a memory location, no subscript is required: int x[5]; fill_array(x, 5, 1); /* better */ or fill_array(&x[0], 5, 1);

Figure 8.6 Data Areas Before Return from fill_array (x, 5, 1);

Preventing Modification To prevent an array from being modified by a function, use the const keyword in the function declaration: int get_min_sub(const double data[], int data_size) {…}

Figure 8.7 Function to Find the Largest Element in an Array

Figure 8.9 Function to Add Two Arrays

Figure 8.10 Function Data Areas for add_arrays(x, y, x_plus_y, 5);

Figure 8.11 Diagram of Function fill_to_sentinel

Figure 8.12 Function Using a Sentinel- Controlled Loop to Store Input Data in an Array

Figure 8.13 Driver for Testing fill_to_sentinel

Stack A B C D

Figure 8.14 Functions push and pop

Figure 8.14 Functions push and pop (cont’d)

Array Search Algorithm Assume the target has not been found. Start with the initial array element Repeat while the target is not found and there are more array elements – If the current element matches the target Set a flag to indicate that the target has been found. – Else Advance to the next array element. If the target was found: – Return the target index as the search result. Else – Return -1 as the search result.

Array Search Flowchart Set flag to false Set counter to 0 flag = true or counter = # of elements current element = target? increment counter set flag = true flag= true? return -1 return counter N N N Y Y Y

Figure 8.15 Function That Searches for a Target Value in an Array

Algorithm for Selection Sort For each value of fill from 0 to n-2 – Find index_of_min, the index of the smallest element in the unsorted subarray list[fill] through list[n-1] – If fill is not the position of the smallest element (index of min): Exchange the smallest element with the one at position fill.

Figure 8.16 Trace of Selection Sort

Figure 8.17 Function select_sort

Two-dimensional Array Two-dimensional array char tictac[3][3]; Function that accepts a two-dimensional array void make_move(char b[][3], int posx, int posy, char piece) { } or void make_move(char b[3][3], int posx, int posy, char piece) { }

Figure 8.18 A Tic-tac-toe Board Stored as Array tictac

Figure 8.19 Function to Check Whether Tic-tac-toe Board Is Filled

Initializing a Two-dimensional Array char tictac[3][3] = { {' ', ' ', ' '}, {' ', ' ', ' '} }

Arrays with Multiple Dimensions ANSI requires C compilers to allow arrays of six dimensions. Two- and three- dimensional arrays are most common int enroll[MAXCRS][5][4]; course campus year

Figure 8.20 Three-Dimensional Array enroll

Processing a Three-Dimensional Array /* Finds and displays number of students in each course */ for (course = 0; course < MAXCRS; ++course) { crs_sum = 0; printf(“Number of students in course %d is %d\n”, course, crs_sum): } for (campus = 0; campus < 5; ++campus) { for (cls_rank = 0; cls_rank < 4; ++cls_rank) { crs_sum += enroll[course][campus][cls_rank]; }

Another Three-Dimensional Array Example /* Finds and displays number of students at each campus */ for (campus = 0; campus < 5; ++course) { campus_sum = 0; printf(“Number of students at campus %d is %d\n”, campus, campus_sum): } for (course = 0; course < MACRS; ++campus) { for (cls_rank = 0; cls_rank < 4; ++cls_rank) { campus_sum += enroll[course][campus][cls_rank]; }

Figure 8.21

Figure 8.22 Hospital Revenue Summary Main Function

Figure 8.23 Function scan_table and Helper Function initialize

Figure 8.23 Function scan_table and Helper Function initialize (cont’d)

Figure 8.24 Function display_table and Helper Functions display_quarter and whole_thousand

Figure 8.24 Function display_table and Helper Functions display_quarter and whole_thousands (cont’d)