Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II.

Slides:



Advertisements
Similar presentations
CHAPTER 10 ARRAYS II Applications and Extensions.
Advertisements

Arrays. Introduction Arrays –Structures of related data items –Static entity - same size throughout program A few types –C-like, pointer-based arrays.
Arrays Programming COMP102 Prog. Fundamentals I: Arrays / Slide 2 Arrays l An array is a collection of data elements that are of the same type (e.g.,
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
 2003 Prentice Hall, Inc. All rights reserved Introduction Arrays –Structures of related data items –Static entity (same size throughout program)
Review (Week1) C++_ the unit of programming is the class from which objects are eventually instantiated. C++ classes contain functions that implement class.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
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.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays 6.3Declaring Arrays 6.4Examples Using Arrays 6.5Passing.
Sorting and Searching. Problem Read in a parameter value n, then read in a set of n numbers. Print the numbers in their original order. Sort the numbers.
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
 2003 Prentice Hall, Inc. All rights reserved Multiple-Subscripted Arrays Multiple subscripts –a[ i ][ j ] –Tables with rows and columns –Specify.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
CSE202: Lecture 14The Ohio State University1 Arrays.
1 Lecture 22:Applications of Arrays Introduction to Computer Science Spring 2006.
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
Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize.
C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Chapter 8 Arrays and Strings
1 Lecture 5: Part 1 Searching Arrays Searching Arrays: Linear Search and Binary Search Search array for a key value Linear search  Compare each.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 19 Thanks for Lecture Slides:
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
計算機程式語言 Lecture 07-1 國立臺灣大學生物機電系 7 7 Arrays.
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 The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with.
Arrays Array –Group of consecutive memory locations –Same name and type To refer to an element, specify –Array name –Position number Format: arrayname.
C Lecture Notes 1 Arrays Lecture 6. C Lecture Notes 2 6.1Introduction Arrays –Structures of related data items –Static entity – same size throughout program.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
 2003 Prentice Hall, Inc. All rights reserved. Using Arrays in Abstract Data Types.
1 Lecture 8 Arrays Part II Sorting Arrays Sorting data  Important computing application  Virtually every organization must sort some data Massive.
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.
1 Arrays and Vectors Chapter 7 Arrays and Vectors Chapter 7.
1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing Arrays to Functions 4.6Sorting Arrays 4.7Case.
Arrays Multi-dimensional initialize & display Sorting Part II.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 Vectors.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Review for Final Exam. Contents 5 questions (20 points each) + 1 bonus question (20 points) – Basic concepts in Chapters 1-4 – Chapters 5-9 – Bonus: Chapter.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
C Lecture Notes 1 Arrays (...cont.). C Lecture Notes 2 6.6Sorting Arrays Sorting data –Important computing application –Virtually every organization must.
 2003 Prentice Hall, Inc. All rights reserved. Outline 1 fig04_03.cpp (1 of 2) 1 // Fig. 4.3: fig04_03.cpp 2 // Initializing an array. 3 #include 4 5.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
C++ Programming Lecture 16 Arrays – Part III The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Opening Input/Output Files ifstream infile; ofstream outfile; char inFileName[40]; char outFileName[40]; coutinFileName;
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.
CHAPTER 3 ARRAYS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Arrays 3.Declaring Arrays 4.Examples Using Arrays 5.Multidimensional Arrays 6.Multidimensional.
SIMPLE Sorting Sorting is a typical operation to put the elements in an array in order. Internal Sorts [for small data sets] selection bubble (exchange)
 2000 Prentice Hall, Inc. All rights reserved Arrays Array –Consecutive group of memory locations –Same name and type To refer to an element, specify.
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 Outline 1 Introduction 2 Arrays 3 Declaring Arrays
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. cout >
Arrays and Records.
Review for Final Exam.
CISC181 Introduction to Computer Science Dr
C++ Programming Lecture 16 Arrays – Part III
4.9 Multiple-Subscripted Arrays
Vectors.
4.9 Multiple-Subscripted Arrays
SIMPLE Sorting Sorting is a typical operation to put the elements in an array in order. Internal Sorts [for small data sets] selection bubble (exchange)
Presentation transcript:

Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Multidimensional Arrays a everything about one dimensional arrays applies * a all elements of the same data type [ ] a just need additional sets of [ ] a a 3-D array has rows, columns, and rank * Except leaving the size out of the formal parameter

Multidimensional Arrays int scores [4] [3] [2]; // assume loaded with 1-24 for(row=0; row<4; row++) { for(col=0; col<3; col++) { for(rank=0; rank<2; rank++) cout<<setw(6)<<scores[row][col][rank]; cout<<endl; // new line for each row }

Multidimensional Arrays { cout <<endl; // start a new line { nums[row][col][rank] cout<<setw(6)<<nums[row][col][rank]; cout<<endl;// start a new line } for(rank=0; rank < 2; rank++) for(col=0; col < 3; col++) for(row=0; row < 4; row++)

A B C D F parallel arrays = two or more arrays in which elements with corresponding indexes are related We WILL do this in the next lab Parallel Arrays Used when related data is of different data types. grade% of class *

Parallel Arrays for(row… for(col… {cout > id[row][col]; cout > grade[row][col]; } OR for(row… for(col… { cout << “Enter id and grade”; cin >> id[row][col] >> grade[row][col]; }

Sum a Row void main(void) { double nums [3][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; double sumRow(double [3] [4]); // prototype cout << “The sum of row 3 is “ << sumRow(nums)<<endl; //function call }

Sum a Row double sumRow(double ary[3][4]) { int col; double total=0; for(col = 0; col < 4; col++) total += ary[ ][col]; return total; } * total += ary[2][col]; //enter row # -1 The sum of row 3 is 42 output The sum of row 3 is 42

Sum a Column void main(void) { double nums [3][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; double sumCol(double [3] [4]); // prototype cout << “The sum of column 3 is “ << sumCol(nums) << endl; //function call }

Sum a Column double sumCol(double ary[3][4]) { int row; double total=0; for(row = 0; row<3; row++) total += ary[row][ ]; return total; } * total += ary[row][2]; //enter col # -1 The sum of column 3 is 21 output The sum of column 3 is 21

Array Review -1 Write a C++ program that adds equivalent elements of the two-dimensional arrays named first and second. Both arrays should have two rows and three columns. For example, element [1][2] of the resulting array should be the sum of first[1][2] and second[1][2]. first second sum *

Sorting Internal Sorts [for small data sets] bubble (exchange) selection External Sorts [for large data sets]

Bubble Sort Put smaller first No change Put smaller first

Bubble Sort Begin again and put smaller first No change Put smaller first

A Bubble Sort Function void bubble_sort(int array[ ], int length) { int j, k, flag=1, temp; for(j=1; j<=length && flag; j++) { flag=0; // false for(k=0; k < (length-j); k++) { if (array[k+1] > array[k]) // > low to high { temp=array[k+1]; // swap array[k+1]= array[k]; array[k]=temp; flag=1; // indicates a swap }}}} }}}} // has occurred

Selection Sort index (k)sm_index 02 swap 21, 9 11 swap 13, swap 21, swap 21,

Selection Sort void sort(double [5]); void swap(double [5], int, int);// prototypes void main(void) {int index; double my_list[ ] = {21, 13, 9, 15, 17}; cout << "\nThe unsorted array is: \n"; for(index=0; index<5; index++) cout << “ “ << my_list[index] << endl; sort(my_list); // function call cout << "\nThe sorted array is: \n"; for(index=0; index<5; index++) cout << “ “ << my_list[index] << endl; }

Selection Sort void sort(double testArray[5]) {int n, k, sm_index, pass=0; double smallest; for(k=0; k<4; k++) // size-1 = number of passes {smallest = testArray[k]; sm_index = k; for(n=k+1; n<5; n++) // size = # elem. to look at if(testArray[n] < smallest) {smallest = testArray[n]; sm_index = n; } swap(testArray, sm_index, k);// call to swap() }

Selection Sort void swap(double testArray[5], int smaller, int position) {// position = current position: k double temp; temp = testArray[position]; testArray[position] = testArray[smaller]; testArray[smaller] = temp; }

Linear Search Pseudocode For all the items in the list Compare the item with the desired item If the item was found Return the index value of the current item (the position of the element in the array) End If End For Return -1 because the item was not found

The “Classic” Linear Search Function int LinearSearch(int list[], int size, int key) {// or “Sequential search” int i; for (i = 0; i < size; i++) { if (list[i] = = key) return i;// return location of element //this will terminate the loop } return -1;// element not in list }

Main for linear search int main() { int LinearSearch(int [], int, int); // prototype const int NUMEL = 10; int nums[NUMEL] = {22,5,67,98,45,32,101,99,73,10}; int item, location; cout << "\nEnter the item you are searching for: "; cin >> item; location = LinearSearch(nums, NUMEL, item); if (location > -1) cout << "The item was found at index location " << location << endl; else cout << "The item was not found in the list\n"; return 0; }

Binary Search List must be in sorted order The function looks at the midpoint If the midpoint is the item, return the location Else, determine if the item is less than or greater than the midpoint Eliminate the side where the item cannot be, and declare a new midpoint Go again. (A recursive function) Half the list is eliminated on each pass

int BinarySearch(int list[], int size, int key) { int left, right, midpt;// list must be in sorted order left = 0;// left end is the first element right = size - 1;// right is the last element while (left <= right){ midpt = (int) ((left + right) / 2); // why integer division? if (key == list[midpt]) return midpt; // if found, the key will be the midpoint else if (key > list[midpt])// eliminate the left half left = midpt + 1; else right = midpt - 1;// else - eliminate the right half }// end while return -1;} // the key was never found

Main for binary search int main() { int BinarySearch(int [], int, int); // prototype const int NUMEL = 10; int nums[NUMEL] = {5,10,22,32,45,67,73,98,99,101}; int item, location; cout << "\nEnter the item you are searching for: "; cin >> item; location = BinarySearch(nums, NUMEL, item); if (location > -1) cout << "The item was found at index location " << location << endl; else cout << "The item was not found in the list\n"; return 0; }

Array Review a is an ordered sequence of data of the same type a can be of any valid data type a can be 1-, 2-, or multi- dimensional a must be declared before used a can be assigned and initialized a element numbering starts at zero

Array Review a use for loops to access (nested for multidimentional) a can be passed back and forth between functions a when sent to functions the actual values are manipulated - not a copy (passed by reference)

Array Review - 6a There is an array of three students each with four exam scores. Assume the scores are known and are: {77, 68, 86, 73}, {96, 87, 89, 78}, {70, 90, 86, 81}. Create a program which will display the lowest grade, the highest grade and the average of the grades to two decimal places.

Array Review - 6b #include using namespace std; const int STUDENTS = 3; // global, so main and all const int EXAMS = 4; // functions can access int mini (int [][EXAMS], int, int); int maxi (int [][EXAMS], int, int); float average(int [], int); void printArray(int [][EXAMS], int, int);

Array Review - 6c void main(void) { int studentGrades[ STUDENTS ][ EXAMS ] = {{77, 68, 86, 73}, {96, 87, 89, 78}, {70, 90, 86, 81}}; cout << "The array is:" << endl; printArray(studentGrades, STUDENTS, EXAMS ); cout<<endl<<endl<<"Lowest grade: " << mini (studentGrades, STUDENTS, EXAMS ) << endl << "Highest grade: " << maxi (studentGrades, STUDENTS, EXAMS )<<endl; for (int person = 0; person < STUDENTS; person++) cout << "The average grade for student " << person << " is " << setiosflags(ios::fixed | ios::showpoint)<<setprecision(2) << average(studentGrades[person], EXAMS) << endl; }

Array Review - 6d int mini(int grades[][EXAMS], int pupils, int tests) { int lowGrade = 100; for (int i = 0; i < pupils; i++) for (int j = 0; j < tests; j++) if (grades[i][j] < lowGrade) lowGrade = grades[i][j]; return lowGrade; } int maxi(int grades[][EXAMS], int pupils, int tests) { int highGrade = 0; for (int i = 0; i < pupils; i++) for (int j = 0; j < tests; j++) if (grades[i][j] > highGrade) highGrade = grades[i][j]; return highGrade; }

Array Review - 6e float average(int setOfGrades[], int tests) { int total = 0; for (int i = 0; i < tests; i++) total += setOfGrades[i]; return (float) total / tests; } void printArray(int grades[][EXAMS], int pupils, int tests) { cout << " [0] [1] [2] [3]"; for (int i = 0; i < pupils; i++) { cout << endl<< "studentGrades[" << i << "] "; for (int j = 0; j < tests; j++) cout << setiosflags(ios::left) << setw(5) << grades[i][j]; }

Array Review - 6f function call: average(studentGrades[person], EXAMS) float average(int setOfGrades[], int tests) {int total = 0; for (int i = 0; i < tests; i++) total += setOfGrades[i]; return total / tests; }

Common Errors ; Not declaring the array ; First element is called zero; last element is one less than the number of elements ; Out of range subscripts - no warning ; Error in the for loop - check the counter ; Not initializing the array

Common Errors ; Aggregate operations not allowed ; Omitting array size - permitted only when declared as a formal parameter initialized in the declaration  If array is /* in */ only, declare the formal parameter as const to prevent accidental modification

Debugging array subscripts recheck array size in declaration, initialization, and for loops Prevention - plan first! Valuation tables Display values with cout C++ Debugger

I really hate this darn machine, I wish they would sell it. It never does quite what I want, But only what I tell it. End Note