Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
 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.
Chapter 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
Chapter 9: Arrays and Strings
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Introduction to Programming with C++ Fourth Edition
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
1 Arrays & functions Each element of an array acts just like an ordinary variable: Like any ordinary variable, you can pass a single array element to a.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Sorting Arrays. Selection Sort  One of the easiest ways to sort the elements of an array is by using the selection sort algorithm.  Assume that the.
Arrays.
Intro to CS – Honors I Basic Sorting GEORGIOS PORTOKALIDIS
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
Chapter 7 Arrays. Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional Arrays.
 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.
Chapter 8 Arrays and Strings
Chapter 7 One-Dimensional Arrays 7.1 Arrays in C One of the more useful features of C is the ability to create arrays for storing a collection of related.
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
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.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
Chapter 8 Arrays Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
11/26/2015 CSI Chapter 10, Part I 1 Introducing Arrays… An array is a collection of sequentially indexed elements, each element having the same.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
Arrays.
1 Parameter passing Call by value The caller evaluates the actual parameters and passes copies of their values to the called function. Changes to the copies.
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 ENERGY 211 / CME 211 Lecture 4 September 29, 2008.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
L what is a void-function? l what is a predicate? how can a predicate be used? l what is program stack? function frame? l what’s call-by-value? l what’s.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Arrays as Function Parameters. CSCE 1062 Outline  Passing an array argument (section 9.3)  Reading part of an array (section 9.4)  Searching and sorting.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
1 Programming in C++ Dale/Weems/Headington Chapter 11 One-Dimensional Arrays.
Chapter 7 Arrays Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Computer Programming BCT 1113
Engineering Problem Solving with C++, Etter
Chapter 7 Arrays Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
C++ Data Types Simple Structured Address Integral Floating
Chapter 7 Arrays. Chapter 7 Arrays Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional.
7 Arrays.
Arrays Kingdom of Saudi Arabia
Review of Everything Arrays
Arrays Lecture 11.
7 Arrays.
Chapter 9: Data Structures: Arrays
Arrays Arrays A few types Structures of related data items
Chapter 7 Arrays. Chapter 7 Arrays Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional.
Presentation transcript:

Chapter 7 Arrays

Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students. int score1, score2; Declare 100 variables to store a test score of 100 students. int score1, score2, …, score100; Is it a smart ways? NO Solution: Arrays

Array a composite structure consisting of a list of data of the same type. Syntax: type name[size]; //1-dimensional array type name[size1][size2]; //2-dimensional array Examples int score[25]; //1-dimensional array int matrix[2][3]; //2-dimensional array

Array Notes Subscripts: the number associated with one element of the array (the index). Subscripts start from 0. Can be any integral type. Can’t be negative. Arrays may store data of any type – including struct and class objects or other arrays. Declaration: Square brackets after identifier indicate array. Number in brackets indicates number of elements in array. Must be a constant. Size of array is determined at compiler time (static allocation); cannot be changed during runtime.

Array Elements Individual elements are accessed by using the name of the array and its subscript (index). The index is written as an expression and must be evaluated before use. int score[8], n=4; cin>> score[0] ; // user input and stored in score[0]. score[2]=3; // assign 3 to value stored in score[2] score[n+1]=8; // assign 8 to value stored in score[5] score[0]++; // increment value stored in score[0] score[n++] = 6; // assign 6 to value stored in score[4] and increase n by 1 (n  5) score[++n] = 10; // increment index to move to next value in the array (score[6]) and assign 10 to it. By incrementing the subscript, we can access entire array in 1 loop. Use a FOR loop to process. int size=8; for (int i=0;i<size;i++) { cout << “Enter the score #” << i ; cin >> score[i]; } We can use WHILE loop, too. int n=0; while (n<size) { cout << “Score[” << n << “]: ” << score[n++] << endl; } score[1] score[2] score[3] score[4] score[5] score[6] score[7] score[0]

Array Memory Allocation Array elements are stored contiguously. Need only know address of score[0]-compiler increments by size of type of array to find next value. Caution: index out of range won’t produce error, just garbage and may overwrite good data. int a = score[8]; score[9] = 10; score[1] score[2] score[3] score[4] score[5] score[6] score[7] score[0]

Array Initialization No array size specified. Numbers of items will be used to determine the size int a[] = {3,4,5,2}; // sets up array from a[0] to a[3] (4 elements) If number of initialized elements is less than array size then remaining elements are initialized to zero. int a[3] = {1}; // {1,0,0}; Initialized all to zero. int a[3] = {0};

Arrays in Functions (Single element) An element of an array can be passed into any function requiring a variable of that type. We can process each element of the array as a single value. Can pass to a function as call-by-value or call- by-reference.

Arrays in Functions (Single element) void main () { int score[5] = {7, 10, 8, 5, 9}; addOne(score[3]); isPass(score[4]); } void addOne (int& point) { point++; } bool isPass (int point) { return (++point >= 8); } score[1] score[2] score[3] score[4] score[0] score[1] score[2] score[3] score[4] score[0] score[1] score[2] score[3] score[4] score[0]

Entire Array as Function Arguments Always passes in functions as call-by-reference. – The array name is the address of the first element. It is called the base address. – The ampersand (&) is implied and not written. The [] in the formal parameter list tells the compiler that it is an array. We also need to pass in the size of the array. The function call just passes in the array name.

Entire Array as Function Arguments void main () { int score[5]; getScore(score, 5); } void getScore (int s[], int size) { for (int i=0; i<size; i++) { cout << “Enter score# ” << i; cin >> s[i]; } ? ? ? ? ? score[1] score[2] score[3] score[4] score[0] score[1] score[2] score[3] score[4] score[0]

Entire Array as Function Arguments void main () { int score[5]; getScore(score, 5); printScore(score, 5); } void getScore (int s[], int size) { for (int i=0; i<size; i++) { cout << “Enter score# ” << i; cin >> s[i]; } void printScore (int s[], int size) { for (int i=0; i<size; i++) { cout << “Score# ” << i << s[i] << endl; s[i]--; } ? ? ? ? ? score[1] score[2] score[3] score[4] score[0] score[1] score[2] score[3] score[4] score[0] score[1] score[2] score[3] score[4] score[0]

const Array Argument Passing in an array is a new kind of argument called an array argument Since arrays are always passed-by-reference, if we want to prevent the contents of the array from changing, use const. The word const in the function declaration prevents us from inadvertently changing the contents of the array. Used in both function prototype and definition, not in function call. Failure to be consistent in using const in both places results in a linkage error.

Entire Array as Function Arguments void main () { int score[5]; getScore(score, 5); printScore(score, 5); } void getScore (int s[], int size) { for (int i=0; i<size; i++) { cout << “Enter score# ” << i; cin >> s[i]; } void printScore (const int s[], int size) { for (int i=0; i<size; i++) { cout << “Score# ” << i << s[i] << endl; // s[i]--; syntax error } ? ? ? ? ? score[1] score[2] score[3] score[4] score[0] score[1] score[2] score[3] score[4] score[0] score[1] score[2] score[3] score[4] score[0]

Functions that Return an Array Since to return an array is to return an address, a special type of variable is used. This is called a pointer. At this point, we have no way to return a whole array. We can, however, omit the const modifier and change the array that way.

Programming with Arrays Partially Filled Arrays – Since array allocation is static, may not use whole array. Choose array size to be largest possible amount but keep track of number of valid values entered. – Must pass in a parameter (int size) to indicate how many spaces have valid data.

Partially Filled Arrays void main () { int score[25], count=0; getScore(score, 25, count); int indexOf5 = search(5, count); } void getScore (int s[], int size, int& num_used) { cout << “Enter up to ” << size << “non-negative numbers. \n” << “Enter a negative number to end.” << endl; int next, index=0; cin >> next; while (next >=0 && index < size) { s[index++] = next; cin >> next; } num_used = index; } Notes: getScore must return number_used (call-by- reference) Process until a sentinel value is read or max-size-1 reached. Functions to process array functions must pass in number_used

Sequential Search of an array Go element by element until either target is found or reach end of list. //Pre-Condition: num_used cannot greater than the declared size // Also, s[0] through s[num_used] have values. //Post-Condition: return the index of the first occurrence of the target. // Otherwise, return -1 int search (const int s[], int num_used, int target) { for (int i=0; i<num_used; i++) { if (s[i] == target) return i; } return -1; }

Find the smallest/largest Number Go element by element to find the smallest/largest number. //Pre-Condition: size: numbers of elements in the array // Also, s[0] through s[size-1] have values. //Post-Condition: return the smallest number in the array. int smallest (const int s[], int size) { int theSmallest = s[0]; for (int i=0; i < size; i++) { if (s[i] < theSmallest) theSmallest = s[i]; } return theSmallest; }

Sorting an Array Arrange the elements of an array in a specific order. Sorting algorithms: – Bubble sort – Selection sort – Insertion sort – Merge sort – Heapsort – Quicksort – …

Selection Sort Algorithm: finds the minimum value, swaps it with the value in the first position, and repeats these steps for the remainder of the list. For Array: Finds the smallest element in an array and swaps it with the element in position 0. Then, finds the smallest element in the remaining array and swaps it with the element in position 1, etc.

Index Of Smallest int IndexOfSmallest (const int a[], int startIndex, int num_used) { int min = a[startIndex], indexOfMin = startIndex; for (int i = startIndex+1; i < num_used; i++) if (a[i] < min) { min = a[i]; // min is the smallest number of a[startIndex] through a[i] indexOfMin = i; } return indexOfMin; } void swap (int& v1, int& v2) { int temp = v1; v1 = v2; v2 = temp; }

SelectionSort() int SelectionSort(int a[], int num_used) { int indexOfNextSmallest; for (int i = 0; i < num_used-1; i++) { indexOfNextSmallest = IndexOfSmallest (a, i, num_used); swap (a[i], a[indexOfNextSmallest ]); } a[0]a[2]a[1]a[5]a[4]a[5]a[7]a[6]a[8]a[9] i = 0 i = 1 i = 2 i = 3 i = 4 i = 5

Multidimensional Arrays Are arrays of arrays Syntax: Type ArrayName[ROW][COL] //2-dimensional Type ArrayName[Width][Height][Depth] //3-dimensional Examples: int matrix[2][3] //2x3 matrix int rubik[3][3][3] //cube

2-Dimensional Arrays Initialization: int matrix[3][3] = {{1,2,3},{4,5,6},{7,8,9}}; if row size is unspecified, it is taken from the number of arrays in the brackets. Must always give column size. int matrix[][3] = { {1,2,3}, {4,5,6} }; // 2x3 int matrix[][3] = { {1,2,3}, {4,5,6}, {7,8,9} }; // 3x3 int matrix[][2] = { {1,2}, {3,4}, {5,6} }; // 3x2 C++ stores all arrays as a single one- dimensional array. The array name is a constant pointer to the first dimensional array matrix[0][0] matrix[0][1] matrix[0][2] matrix[1][0] matrix[1][1] matrix[1][2] matrix[2][3] Row 2 Row 3 Row 1 Col 2Col 3Col 1