Arrays.

Slides:



Advertisements
Similar presentations
An Array A sequence of elements of a particular type Each element in the array has an index which gives its position in the sequence An array is declared.
Advertisements

1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
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. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
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.,
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
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.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
Understanding Arrays and Pointers Object-Oriented Programming Using C++ Second Edition 3.
Computer Science 1620 Arrays. Problem: Given a list of 5 student grades, adjust the grades so that the average is 70%. Program design: 1. read in the.
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.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Arrays.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
Chapter 7 Arrays. Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional Arrays.
Arrays One-Dimensional initialize & display Arrays as Arguments Part I.
Lists in Python.
C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional.
Chapter 8 Arrays and Strings
1 Problem Solving with C++ The Object of Programming Walter Savitch Chapter 9 ARRAYS Slides by David B. Teague, Western Carolina University, A Constituent.
Searching and Sorting, Template Functions, and Vectors ITK 169 Fall 2003.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 8 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.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
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.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Arrays Dr. Jose Annunziato. Arrays Up to this point we have been working with individual primitive data types Arrays allow working with multiple instances.
CHAPTER 6 ARRAYS IN C++ 2 nd Semester King Saud University College of Applied studies and Community Service CSC 1101 By: Fatimah Alakeel Edited.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
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.
Arrays.
Module 1: Array ITEI222 - Advance Programming Language.
Lecture 8 – Array (Part 1) FTMK, UTeM – Sem /2014.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
For Friday Read No quiz Program 6 due. Program 6 Any questions?
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
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.
Chapter 7: Arrays. 7.1 Arrays Hold Multiple Values.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Arrays Hold Multiple Values 7.1.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
Chapter 6 Arrays in C++ 2nd Semester King Saud University
Chapter 7 Arrays Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Bill Tucker Austin Community College COSC 1315
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. cout >
Chapter 7 Arrays Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
New Structure Recall “average.cpp” program
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.
One-Dimensional Array Introduction Lesson xx
Data type List Definition:
Review of Everything Arrays
Arrays Lecture 11.
Chapter 9: Data Structures: Arrays
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:

Arrays

One Dimensional Arrays A data structure used for storage of a collection of data items that are all the same type. Individual data items are stored in adjacent cells of main memory.

Declaring Arrays Assign one variable name to a collection of two or more adjacent memory cells. Must declare: type array-name [size];

Declaring Arrays Examples: double temperature [5];

double temperature [5]; 12.3 temperature [0] 7.5 temperature [1] 65.0 temperature [2] 72.1 temperature [3] 87.5 temperature [4]

double temperature [5]; 12.3 temperature [0] 7.5 temperature [1] 65.0 temperature [2] Elements 72.1 temperature [3] 87.5 temperature [4]

double temperature [5]; 12.3 temperature [0] 7.5 temperature [1] 65.0 temperature [2] Subscript or Index 72.1 temperature [3] 87.5 temperature [4]

Printing the Array cout<<temperature [0]; cout<<temperature [1]; cout<<temperature [2]; cout<<temperature [3]; cout<<temperature [4];

Printing the Array for(int i=0; i<5; i++) { cout<<temperature[i]<<endl; } Subscript Variable

Assignment Statement temperature [4] = 12.7; or N = 4; temperature [N] = 12.7;

Three ways to get values into array elements Use assignment statements Initialize arrays in the variable declaration statement Read input values into the array from the keyboard or from a file

Reading Arrays for(int i=0; i<5; i++) { cout<<“enter temperature “<<i<< “ “; cin>>temperature[i]; } cin>>temperature[0]>>temperature[1]>> temperature[2]>>temperature[3]>> temperature[4];

Average Temperature double sum = 0.0; for(int i=0; i<5; i++) { sum += temperature[i]; } average = sum / 5.0;

More About Array Declarations We may use constants for the size in an array declaration: const int SIZE = 6; int score[SIZE];

int score [6]; declaration: score: 49 75 65 90 77 70 49 75 65 90 77 70 index: 0 1 2 3 4 5 (Subscript) score[2] = 65; score[0] = 49;

Accessing the Individual Elements of an Array If a variable represents an array, we refer to the whole array when we use just the name of the variable ex. score

Accessing Individual Elements We access a particular array element by using the array name followed by the index in square brackets: sumTwo = score[3] + score[0];

1. Assigning Values We cannot use assignment statements with entire arrays (some languages allow this, but most, including C++, do not handle it) Instead, we must assign values to individual elements We can use them as values in assignment statements: score[0] = 30; grade[3] = ‘A’; price[2] = 10.39; scalar variable - a single data item vs. data structure - a data aggregate

Using Array Elements All of the following are valid: score[0] = 4; score[0] += 7; score[1] = score[0] -2; score[2] = score[1] + 5 * score[0]; score[j] = score[j + 1]; Note: index can be any integral expression.

2. Declaration-Initialization We can put initial values into an array at declaration time We must list all of the values: they must all be constants: int num[5] = {58, 43, 60, 21, 38}; We don’t have to specify the dimension of the array when we initialize it: int x[ ] = {4, 8, 30, 21, 56, 87}; will be an array of six elements Exception: you may initialize all elements of an array to 0 with int score_ary[10] = {0};

Array Practice Lec p. 132 Declare an array to hold the tax for up to 10 different sales. Declare an array to hold the final letter grades for a class with up to 40 students Declare an array of integers which holds the final average for those 40 students and initialize its values to 0 Declare an array of characters called letter_ary with initial values ‘a’, ‘d’, ‘y’, and ‘w’. What is the value of letter_ary[1]?

3. Enter from keyboard or file A for loop is an ideal way to read data into an array. This loop assumes we’re reading exactly 5 elements. for (i = 0; i < 5; i++) { cout << “Please enter a score: ”; cin >> score[i]; }

More Array Practice Lec p. 133 Write a loop to initialize all 50 elements of array salary_ary to 100. Write C++ code to read values from the keyboard to fill the array scores. Input should stop when a negative number is entered. The maximum size of the array is in a constant ARR_SIZE. Write C++ code to add up the first num_elements values in the array my_vals and store the sum in the variable my_sum.

More Array Practice Assume that your third array already has values. Now write a function to put the appropriate letter grades into the second function.

Error! Must be a constant #include <iostream> using namespace std; int main() { int x[10] = {0, 1,2,3,4,5,6,7,8,9}; int n; cin >> n; int y[n]; //Line 10 - Here we have (illegally) declared //an array of non-constant size for( int i = 0; i < n; i++) cout << (y[i] = x[i]) << " " ; cout<< endl; return 0; } Must be a constant

Display 9.1 Program using an Array //Reads in 5 scores and shows how much each //score differs from the highest score. #include <iostream> using namespace std; int main( ) { int i, score[5], max; cout << "Enter 5 scores:\n"; cin >> score[0]; max = score[0]; for (i = 1; i < 5; i++) { cin >> score[i]; if (score[i] > max) max = score[i]; //max is the largest of the values score[0],..., score[i]. } cout << "The highest score is " << max << endl << "The scores and their\n" << "differences from the highest are:\n"; for (i = 0; i < 5; i++) cout << score[i] << " off by " << (max - score[i]) << endl; return 0;

Dice Example Write a C++ program to find the frequency distribution of all possible sums of the roll of two dice.

What Do We Do with Arrays? The most common tasks we perform with arrays are to: Load information into an array for later processing Process each element of an array Find a particular element in an array Write out the contents of an array

Importance of Loops Since we usually want to do something with all of the elements of an array, one at a time, we use loops constantly in array processing Sometimes pre-testing loops are appropriate Most often, we use counting loops that start with the first index and end with the last index

Using Arrays with Functions We can pass individual array elements to functions either by value or by reference treat array element same as other variables in the call prototype: void modifyElement(int num); call: modifyElement(arr[3]); function header: void modifyElement(int num) { In prototype - note empty square brackets [ ] - allow function to be called with different arrays of different dimensions—(actually could be any dimension when called whether the brackets are empty or not; that’s just the way C/C++ always works (MEC)) Call - no brackets

Arrays and Functions, cont. It’s often useful to have a function which passes an entire array as a parameter Prototype: void ReadScores(int score[], int NumPlayers); Call: ReadScore(score, NumPlayers); Header: void ReadScores(int score[], int NumPlayers);

Arrays and Functions, cont. Once inside the function: we handle the elements just as we would elsewhere: ReadScores(int score[], int NumPlayers) { int i; for (i = 0; i < NumPlayers; i++) { cin >> score[i]); } }

Note! We cannot return arrays However, if we pass an array to a function, we can modify its contents. So arrays are as if passed by reference. To keep the elements of an array from being accidentally modified in a function use the const keyword in the prototype and header: void PrintScores(const int score[],int numPlayers);

Parallel Arrays Sometimes we have more than one piece of information to go in our array. For example, we might want an array of students Each one should have an ID number, an average, and a letter grade We would use three arrays an ID array an average array and a letter grade array The items found at a given index would all relate to the same student

Parallel Arrays ID_arr: 222 123 445 346 771 708 index: 0 1 2 3 4 5 222 123 445 346 771 708 index: 0 1 2 3 4 5 avg_arr: 87.5 75.2 94.0 90.0 77.9 83.9 index: 0 1 2 3 4 5 grade_arr: B C A A C B index: 0 1 2 3 4 5

Arrays of Structures struct StudentInfo { to use members: int stu_id; double avg; char grade; } to declare: StudentInfo Our_class[40]; to use members: Our_class[1].stu_id = 123; Our_class[0].grade = ‘A’;

More Array Practice Write a loop to initialize all 50 elements of array salary_ary to 100. Suppose array elements chairs_ary[0] through chairs_ary[49] hold the number of chairs in Room 101 through 150, respectively. Write a loop to print the room number and number of chairs for each room.

More Practice Given an array containing the basketball scores for the 26 games played by the Redbirds this season, write a function to find and return the highest score to the calling function. Also write the function prototype and function call.

Array and File Practice Assume you have a file containing information about a store’s inventory. Each line of the file has a part number, a price, and a number on hand. Write a function to read data from this file into three parallel arrays. Remember that we don’t know ahead of time how many parts there are, but we will need to know later in the program. Note that the maximum number of parts does not need to be known in order to write the function.

PROGRAMMING EXAMPLE: Searching an Array The tasks of searching a data structure and sorting (rearranging data in a data structure to obey some order relation) and analysis to determine the time and space these tasks require as a function of the size of the data structure covers much of Computer Science. We illustrate the search task using the sequential search algorithm on an array in Display 9.11. This algorithm examines each element of the array in turn until the element is found, or there are no more array elements to examine.

Shows the difference between each of a list of golf scores and their average. #include <iostream> using namespace std; const int MAX_NUMBER_SCORES = 10; void fill_array(int a[ ], int size, int& number_used); double compute_average(const int a[ ], int number_used); void show_difference(const int a[ ], int number_used); int main( ) { int score[MAX_NUMBER_SCORES], number_used; cout << "This program reads golf scores and shows\n" << "how much each differs from the average.\n"; cout << "Enter golf scores:\n"; fill_array(score, MAX_NUMBER_SCORES, number_used); show_difference(score, number_used); return 0; }

void fill_array(int a[ ], int size, int& number_used) { cout << "Enter up to " << size << " nonnegative whole numbers.\n" << "Mark the end of the list with a negative number.\n"; int next, index = 0; cin >> next; while ((next >= 0) && (index < size)) { a[index] = next; index++; } number_used = index;

double compute_average(const int a[], int number_used) { double total = 0; for (int index = 0; index < number_used; index++) total = total + a[index]; if (number_used > 0) { return (total/number_used); } else { cout << "ERROR: number of elements is 0 in compute_average.\n" << "compute_average returns 0.\n"; return 0;

void show_difference(const int a[ ], int number_used) { double average = compute_average(a,number_used); cout << "Average of the " << number_used << " scores = " << average << endl << "The scores are:\n"; for (int index = 0; index < number_used; index++) cout << a[index] << " differs from average by " << (a[index] - average) << endl; }

Searches a partially filled array of nonnegative integers. const int DECLARED_SIZE = 20; void fill_array(int a[ ], int size, int& number_used); int search(const int a[ ], int number_used, int target); int main( ) { int arr[DECLARED_SIZE], list_size, target; fill_array(arr, DECLARED_SIZE, list_size); char ans; int result; do { cout << "Enter a number to search for: "; cin >> target; result = search(arr, list_size, target); if (result == -1) cout << target << " is not on the list.\n"; else cout << target << " is stored in array position " << result << endl << "(Remember: The first position is 0.)\n"; cout << "Search again?(y/n followed by return): "; cin >> ans; }while ((ans != 'n') && (ans != 'N')); cout << "End of program.\n"; return 0; }

void fill_array(int a[ ], int size, int& number_used) { cout << "Enter up to " << size << " nonnegative whole numbers.\n" << "Mark the end of the list with a negative number.\n"; int next, index = 0; cin >> next; while ((next >= 0) && (index < size)) { a[index] = next; index++; } number_used = index;

int search(const int a[ ], int number_used, int target) { int index = 0; bool found = false; while ((!found) && (index < number_used)) if (target == a[index]) found = true; else index++; if (found) return index; return -1; }

PROGRAMMING EXAMPLE: Sorting an Array Sorting an array means rearranging data in a data structure to obey some order relation. An array that contains objects that can be compared is sorted if for every pair of indices i and j. if i < j then array[i] <= array[j] Said differently: a[0] <= a[1] <= a[2] <= . . . <= a[number_used - 1] We illustrate sorting using the selection sort algorithm in Display 9.13. The array is partially filled so we must pass an additional array parameter that specifies how many array elements are used.

Selection Sort

Tests the procedure sort. void fill_array(int a[ ], int size, int& number_used); void sort(int a[ ], int number_used); void swap_values(int& v1, int& v2); int index_of_smallest(const int a[ ], int start_index, int number_used); int main( ) { cout << "This program sorts numbers from lowest to highest.\n"; int sample_array[10], number_used; fill_array(sample_array, 10, number_used); sort(sample_array, number_used); cout << "In sorted order the numbers are:\n"; for (int index = 0; index < number_used; index++) cout << sample_array[index] << " "; cout << endl; return 0; }

void fill_array(int a[ ], int size, int& number_used) { cout << "Enter up to " << size << " nonnegative whole numbers.\n" << "Mark the end of the list with a negative number.\n"; int next, index = 0; cin >> next; while ((next >= 0) && (index < size)) { a[index] = next; index++; } number_used = index;

void sort(int a[ ], int number_used) { int index_of_next_smallest; for (int index = 0; index < number_used - 1; index++) {//Place the correct value in a[index]: index_of_next_smallest = index_of_smallest(a, index, number_used); swap_values(a[index], a[index_of_next_smallest]); //a[0] <= a[1] <=...<= a[index] are the smallest of the original array //elements. The rest of the elements are in the remaining positions. } void swap_values(int& v1, int& v2) { int temp; temp = v1; v1 = v2; v2 = temp;

int index_of_smallest(const int a[ ], int start_index, int number_used) { int min = a[start_index], index_of_min = start_index; for (int index = start_index + 1; index < number_used; index++) if (a[index] < min) { min = a[index]; index_of_min = index; //min is the smallest of a[start_index] through a[index] } return index_of_min;

Arrays of Structs( or Classes) An arrray with struct elements: struct WindInfo { double velocity; // in miles per hour char direction; // ‘N’, ‘S’, ‘E’, ‘W’ }; WindInfo data_point[10]; To fill the arrrays data_point: for (int i = 0; i < 1-; i++) cout<<"Enter velocity for data point numbered: "<< i; cin >> data_point[i].velocity; cout<<"Enter direction for data point numbered: "<< i; cin >> data_point[i].direction; }

Arrays as Struct (or Class) Members A structure or a class can have an array as a member. If you have to keep track of practice times for swimming a particular distance, you might use this struct struct Data { double time[10]; int distance; }; Data my_best; You can use this to set the distance: my_best.distance = 20; You can use this to set the time array: cout<< "Enter ten times in seconds: \n"; for(int i = 0; i < 10; i++) cin >> my_best.time[i];

Program Using an Array of Objects //Reads in 5 amounts of money and shows //how much each amount differs from lgst #include <iostream> using namespace std; #include "money.h" int main( ) { Money amount[5], max; int i; cout << "Enter 5 amounts of money:\n"; cin >> amount[0]; max = amount[0]; for (i = 1; i < 5; i++) { cin >> amount[i]; if (max < amount[i]) max = amount[i]; //max is the largest of amount[0],...,[i]. } Money difference[5]; for (i = 0; i < 5; i++) difference[i] = max - amount[i]; cout << "The highest amount is " << max << endl; cout << "The amounts and their “ <<“differences from the largest “ <<“are:\n"; { cout << amount[i] << " off by " << difference[i] << endl; } return 0;