7 Arrays.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

5 5 Arrays. OBJECTIVES In this lecture we will learn:  Case switch  To use the array data structure to represent a set of related data items.  To declare.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
Arrays Chapter 6.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
 2006 Pearson Education, Inc. All rights reserved Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays and Vectors.
 2006 Pearson Education, Inc. All rights reserved Arrays and Vectors.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
 2007 Pearson Education, Inc. All rights reserved C Arrays.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
Chapter 8 Arrays and Strings
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Algorithm and Programming Array Dr. Ir. Riri Fitri Sari MM MSc International Class Electrical Engineering Dept University of Indonesia 15 March 2009.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
 2008 Pearson Education, Inc. All rights reserved Arrays and Vectors.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
1 Arrays and Vectors Chapter 7 Arrays and Vectors Chapter 7.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
CHAPTER 07 Arrays and Vectors (part II). OBJECTIVES In this part you will learn:  To pass arrays to functions.  Basic searching techniques.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
 2008 Pearson Education, Inc. All rights reserved Arrays and Vectors.
 2006 Pearson Education, Inc. All rights reserved Arrays and Vectors.
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.
7 Arrays and Vectors.
Computer Programming BCT 1113
© 2016 Pearson Education, Ltd. All rights reserved.
Arrays Outline 1 Introduction 2 Arrays 3 Declaring Arrays
CSC 113: Computer Programming (Theory = 03, Lab = 01)
JavaScript: Functions.
8 Pointers.
C Arrays.
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
C Arrays.
7 Arrays.
7 Arrays.
Chapter 9 - Arrays Outline 6.1 Introduction 6.2 Arrays
Arrays Kingdom of Saudi Arabia
Arrays Outline Introduction Arrays Declaring Arrays
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
4.9 Multiple-Subscripted Arrays
MSIS 655 Advanced Business Applications Programming
6 C Arrays.
9-10 Classes: A Deeper Look.
7 Arrays and Vectors.
Capitolo 4 - Arrays Outline 4.1 Introduction 4.2 Arrays
Arrays Arrays A few types Structures of related data items
Lecture 2 Arrays & Pointers May 17, 2004
Chapter 3 Arrays Dr. A. PHILIP AROKIADOSS Assistant Professor
Lecture 2 Arrays & Pointers September 7, 2004
7 Arrays and Vectors.
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
9-10 Classes: A Deeper Look.
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

7 Arrays

7.1 Introduction 7.2 Arrays 7.3 Declaring Arrays 7.4 Examples Using Arrays 7.5 Passing Arrays to Functions 7.6 Case Study: Class GradeBook Using an Array to Store Grades 7.7 Searching Arrays with Linear Search 7.8 Sorting Arrays with Insertion Sort 7.9 Multidimensional Arrays 7.10 Case Study: Class GradeBook Using a Two-Dimensional Array 7.11 Introduction to C++ Standard Library Class Template vector 7.12 (Optional) Software Engineering Case Study: Collaboration Among Objects in the ATM System 7.13 Wrap-Up

7.1 Introduction Arrays Data structures containing related data items of the same type Always remain the same size once created Are “fixed-size” entities Character arrays can also represent strings Dynamically allocated (pointer-based) arrays LATER!!!

7.2 Arrays Array Consecutive group of memory locations All of which have the same type Index (also called subscript) Position number used to refer to a specific location/element Place in square brackets Must be positive integer or integer expression First element has index zero Example (assume a = 5 and b = 6) c[ a + b ] += 2; Adds 2 to array element c[ 11 ]

7.2 Arrays Brackets used to enclose an array subscript are actually an operator in C++ C++ has no array bounds checking Does not prevent the computer from referring to an element that does not exist Could lead to serious execution-time errors

Common Programming Error Referring to an element outside the array bounds is an execution-time logic error. It is not a syntax error. Portability Tip The (normally serious) effects of referencing elements outside the array bounds are system dependent. Often this results in changes to the value of an unrelated variable or a fatal error that terminates program execution.

Fig.7.2 | Operator precedence and associativity.

7.3 Declaring Arrays Declaring an array Arrays occupy space in memory Programmer specifies type and number of elements int c[ 12 ]; Array’s size must be an integer constant greater than zero Arrays can be declared to contain values of any non-reference data type Multiple arrays of the same type can be declared in a single declaration Use a comma-separated list of names and sizes

7.4 Initializing Arrays The elements of local arrays have garbage values You can initialize the elements at the time of array declaration, using an initializer list Items enclosed in braces ({}) Items in a list separated by commas int n[] = { 10, 20, 30, 40, 50 }; Since the array size is omitted in the declaration, the compiler determines the size of the array based on the size of the initializer list Creates a five-element array The array elements are initialized with the values of 10, 20, 30, 40, 50, respectively

7.4 Initializing Arrays The elements of local arrays have garbage values You can initialize the elements at the time of array declaration, using an initializer list If fewer initializers than elements in the array Remaining elements are initialized to zero int n[ 10 ] = { 0 }; Explicitly initializes the first element to zero Implicitly initializes the remaining nine elements to zero If more initializers than elements in the array Compilation error

7.4 Specifying the Array Size You can specify the array size with a constant variable Using constant variables to specify array sizes makes programs more scalable and eliminates “magic numbers” Constant variables (name constants or read-only variables) Declared using the const qualifier Must be initialized with a constant expression when they are declared and cannot be modified thereafter Common Programming Error 7.4: Not assigning a value to a constant variable when it is declared is a compilation error Common Programming Error 7.5: Assigning a value to a const. variable in an executable statement is a compilation error. Can be placed anywhere a constant expression is expected

Common Programming Error Only constants can be used to declare the size of automatic and static arrays. Not using a constant for this purpose is a compilation error. Good Programming Practice Defining the array size as a constant variable instead of a literal constant makes programs clearer. This technique eliminates so-called magic numbers. For example, repeatedly mentioning the size 10 in array-processing code for a 10-element array gives the number 10 an artificial significance and can unfortunately confuse the reader when the program includes other 10s that have nothing to do with the array size.

Simple Example Write a code fragment that reads grades from a user and summarizes the distribution of these grades creating a histogram Read the grades until the user enters an invalid grade int hist[11] = {0}; cin >> grade; while (grade >= 0 && grade <= 100){ hist[ grade/10 ]++; }

7.4 Character Arrays Character arrays can be used to store and manipulate strings Arrays may be of any type, including chars We can store character strings in char arrays Can be initialized using a string literal char string1[] = "Hi"; is equivalent to char string1[] = { 'H', 'i', '\0' }; Array contains each character plus a special string- termination character called the null character ('\0')

7.4 Character Arrays Character arrays can be used to store and manipulate strings A character array representing a null-terminated string can be output with cout and << cout << string1; Can also input a string directly into a character array from the keyboard using cin and >> cin >> string1; cin >> may read more characters than the array can store Common Programming Error: Not providing cin >> with a character array large enough to store a string typed at the keyboard can result in loss of data in a program and other serious runtime errors

7.5 Passing Arrays to Functions To pass an array argument to a function void modifyArray( int arr[], int arraySize ); Specify the array name without brackets Suppose the array hourlyTemperatures is declared as int hourlyTemperatures[ 24 ]; The function call should be modifyArray( hourlyTemperatures, 24 ); and this call passes array hourlyTemperatures and its size to the function modifyArray You should pass the array size as another argument so the function can know the number of elements in the array

7.5 Passing Arrays to Functions A function call passes the starting address of an array So the function knows where the array is located in memory However, the function does not know where the array ends Thus, you have to pass the array size as another parameter A caller gives the called function a direct access to the caller’s data (the elements of the array) The called function can manipulate this data (array elements)

7.5 Passing Arrays to Functions Functions that take arrays as arguments Function parameter list must specify array as a parameter void modArray( int b[], int arraySize ); The array parameter may include the size of the array (inside the square brackets) The compiler will ignore it, though The compiler only cares about the address of the first element Function prototypes may include parameter names But the compiler will ignore them Parameter names may be left out of the function prototypes

7.5 Passing Arrays to Functions const array parameters Qualifier const Prevent modification of the values of array elements in the caller by code in the called function Elements in the array are constant in the function body Enables the programmer to prevent accidental modification of data

Example: Extend class GradeBook to store grades of multiple students public: const static int studentNo = 10; GradeBook(int, const int []); // ... private: int courseNo; int grades[studentNo]; }; GradeBook::GradeBook(int no, const int S[]){ courseNo = no; for (int i = 0; i < studentNo; i++) grades[i] = S[i]; } int main(){ int A[GradeBook::studentNo]; GradeBook G(201, A); return 0;

Example: Extend class GradeBook to store grades of multiple students static data members Also called class variables Variables for which each object of a class does not have a separate copy One copy is shared among all objects of the class Can be accessed even when no objects of the class exist Use the class name followed by the binary scope resolution operator and the name of the static data member

7.9 Multidimensional Arrays Multidimensional arrays with two dimensions (2-D arrays) Represent tables of values with rows and columns In general, an array with m rows and n columns is called an m-by-n array Elements referenced with two subscripts ([ x ][ y ]) int a[ 3 ][ 4 ]; Multidimensional arrays can have more than two dimensions

7.9 Multidimensional Arrays Initializing two-dimensional arrays Initializing a 2-D array b using an initializer list int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; 1 and 2 initialize b[ 0 ][ 0 ] and b[ 0 ][ 1 ] 3 and 4 initialize b[ 1 ][ 0 ] and b[ 1 ][ 1 ] int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; Row 0 contains values 1 and 0 (implicitly initialized to zero) Row 1 contains values 3 and 4

7.9 Multidimensional Arrays Multidimensional array parameters Size of the first dimension is not required Similar to passing a one-dimensional array Size of the subsequent dimensions are required The compiler must know how many elements to skip to move to the second element in the first dimension void printArray( const int a[][ 3 ] ); The function will skip row 0’s 3 elements to access row 1’s elements (for example to access a[ 1 ][ x ])

Example: Extend class GradeBook to store multiple grades of multiple students public: const static int studentNo = 10; const static int testNo = 3; GradeBook(int, const int [][testNo]); double getAverage(const int [], int); void displayStudentAverages(); private: int courseNo; int grades[studentNo][testNo]; }; int main(){ int A[GradeBook::studentNo][GradeBook::testNo]; // ... GradeBook G(201, A); G.displayStudentAverages(); return 0; }

GradeBook::GradeBook(int no, const int S[][testNo]){ courseNo = no; for (int i = 0; i < studentNo; i++) for (int j = 0; j < testNo; j++) grades[i][j] = S[i][j]; } double GradeBook::getAverage(const int A[], int no){ double avg = 0.0; for (int i = 0; i < no; i++) avg += A[i]; if (no) return avg / no; return 0; void GradeBook::displayStudentAverages(){ // call the getAverage function for the i-th student cout << << endl;