Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 1 Chapter 6 Arrays.

Slides:



Advertisements
Similar presentations
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Advertisements

Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
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 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.,
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 8 Multidimensional.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
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.
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
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.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 7 Multidimensional.
Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 7 Single-Dimensional.
 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
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
Programming Fundamentals I (COSC-1336), Lecture 8 (prepared after Chapter 7 of Liang’s 2011 textbook) Stefan Andrei 4/23/2017 COSC-1336, Lecture 8.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 8 Multidimensional Arrays.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 7 Multidimensional.
Chapter 6 Arrays.
CHAPTER: 12. Array is a collection of variables of the same data type that are referenced by a common name. An Array of 10 Elements of type double.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 8 Multidimensional Arrays.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 6 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.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
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 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 7 Single-Dimensional Arrays and C-Strings.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Multidimensional.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
1 Chapter 7 Pointers and C-Strings. 2 Objectives  To describe what a pointer is (§7.1).  To learn how to declare a pointer and assign a value to it.
Computer Programming Arrays 1. Question #1 2 Question Choose the correct answer..
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 7 Multidimensional Arrays.
Objectives You should be able to describe: One-Dimensional Arrays
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Lecture 7: Arrays Michael Hsu CSULA 3 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average.
Chapter 7 Pointers and C-Strings
Chapter 6 Arrays in C++ 2nd Semester King Saud University
Computer Programming BCT 1113
Chapter 6 Arrays DDC 2133 Programming II.
Chapter 6 Arrays Lecturer: Mrs Rohani Hassan
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. cout >
Chapter 7 Single-Dimensional Arrays
Chapter 6 Arrays Solution Opening Problem
Chapter 5 Arrays Introducing Arrays
CSC138: Structured Programming
Chapter 7 Single-Dimensional Arrays and C-Strings
Chapter 6 Arrays.
Introducing Arrays Array is a data structure that represents a collection of the same types of data. From resourses of Y. Daniel Liang, “Introduction.
Presentation transcript:

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Motivations Often you will have to store a large number of values during the execution of a program. Suppose, for instance, that you need to read one hundred numbers, compute their average, and find out how many numbers are above the average. Your program first reads the numbers and computes their average, and then compares each number with the average to determine whether it is above the average. The numbers must all be stored in variables in order to accomplish this task. You have to declare one hundred variables and repeatedly write almost identical code one hundred times. From the standpoint of practicality, it is impossible to write a program this way. So, how do you solve this problem?

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Objectives F To describe why an array is necessary in programming (§7.1). F To declare arrays (§7.2.1). F To access array elements using indexed variables (§7.2.2). F To initialize the values in an array (§7.2.3). F To program common array operations (displaying arrays, summing all elements, finding min and max elements, random shuffling, shifting elements) (§7.2.4). F To apply arrays in the LottoNumbers and DeckOfCards problems (§§ ). F To develop and invoke functions with array arguments (§§ ). F To develop functions involving array parameters in the CountLettersInArray problem (§7.7). F To search elements using the linear (§7.8.1) or binary search algorithm (§7.8.2). F To sort an array using the selection sort (§7.9.1) F To sort an array using the insertion sort (§7.9.2). F To process strings using C-strings (§7.10).

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Introducing Arrays Array is a data structure that represents a collection of the same types of data.

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Declaring Array Variables datatype arrayName[arraySize]; Example: double myList[10]; C++ requires that the array size used to declare an array must be a constant expression. For example, the following code is illegal: int size = 4; double myList[size]; // Wrong But it would be OK, if size is a constant as follow: const int size = 4; double myList[size]; // Correct

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Arbitrary Initial Values When an array is created, its elements are assigned with arbitrary values.

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Indexed Variables The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arraySize-1. In the example in Figure 6.1, myList holds ten double values and the indices are from 0 to 9. Each element in the array is represented using the following syntax, known as an indexed variable: arrayName[index]; For example, myList[9] represents the last element in the array myList.

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Using Indexed Variables F After an array is created, an indexed variable can be used in the same way as a regular variable. For example, the following code adds the value in myList[0] and myList[1] to myList[2]. m yList[2] = myList[0] + myList[1]; F The following loop assigns 0 to myList[0], 1 to myList[1],…, and 9 to myList[9]. for (int i=0;i<10;i++) { m yList[i] =i; }

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved No Bound Checking C++ does not check array’s boundary. So, accessing array elements using subscripts beyond the boundary (e.g., myList[-1] and myList[11]) does not does cause syntax errors, but the operating system might report a memory access violation.

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Array Initializers Declaring, creating, initializing in one step: dataType arrayName[arraySize] = {value0, value1,..., valuek}; double myList[4] = {1.9, 2.9, 3.4, 3.5};

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Declaring, creating, initializing Using the Shorthand Notation double myList[4] = {1.9, 2.9, 3.4, 3.5}; This shorthand notation is equivalent to the following statements: double myList[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved CAUTION Using the shorthand notation, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. For example, the following is wrong: double myList[4]; myList = {1.9, 2.9, 3.4, 3.5};

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved I mplicit Size C++ allows you to omit the array size when declaring and creating an array using an initilizer. For example, the following declaration is fine: double myList[] = {1.9, 2.9, 3.4, 3.5}; C++ automatically figures out how many elements are in the array.

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Partial Initialization C++ allows you to initialize a part of the array. For example, the following statement assigns values 1.9, 2.9 to the first two elements of the array. The other two elements will be set to zero. Note that if an array is declared, but not initialized, all its elements will contain “garbage”, like all other local variables. double myList[4] = {1.9, 2.9};

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Initializing Character Arrays char city[] = {'D', 'a', 'l', 'l', 'a', 's'}; char city[] = "Dallas"; This statement is equivalent to the preceding statement, except that C++ adds the character '\0', called the null terminator, to indicate the end of the string, as shown in Figure 6.2.

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Initializing arrays with random values The following loop initializes the array myList with random values between 0 and 99: const int ARRAY_SIZE=10; double myList[ARRAY_SIZE]; for (int i = 0; i < ARRAY_SIZE; i++) { myList[i] = rand() % 100; }

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Printing arrays To print an array, you have to print each element in the array using a loop like the following: for (int i = 0; i < ARRAY_SIZE; i++) { cout << myList[i] << " "; }

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Printing Character Array For a character array, it can be printed using one print statement. For example, the following code displays Dallas: char city[] = "Dallas"; cout << city;

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Copying Arrays Can you copy array using a syntax like this? list = myList; This is not allowed in C++. You have to copy individual elements from one array to the other as follows: for (int i = 0; i < ARRAY_SIZE; i++) { list[i] = myList[i]; }

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Summing All Elements Use a variable named total to store the sum. Initially total is 0. Add each element in the array to total using a loop like this: double total = 0; for (int i = 0; i < ARRAY_SIZE; i++) { total += myList[i]; }

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Finding the Largest Element Use a variable named max to store the largest element. Initially max is myList[0]. To find the largest element in the array myList, compare each element in myList with max, update max if the element is greater than max. double max = myList[0]; for (int i = 1; i < ARRAY_SIZE; i++) { if (myList[i] > max) max = myList[i]; }

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Example: Testing Arrays #include using namespace std; int main() { const int TOTAL_NUMBERS = 6; int numbers[TOTAL_NUMBERS]; // Read all numbers for (int i = 0; i < TOTAL_NUMBERS; i++) { cout << "Enter a number: "; cin >> numbers[i]; } This program reads six integers, finds the largest of them, and counts its occurrences. TestArray.cpp

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved // Find the largest int max = numbers[0]; for (int i = 1; i < TOTAL_NUMBERS; i++) { if (max < numbers[i]) max = numbers[i]; } // Find the occurrence of the largest number int count = 0; for (int i = 0; i < TOTAL_NUMBERS; i++) { if (numbers[i] == max) count++; } TestArray.cpp

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved // Display the result cout << "The array is "; for (int i = 0; i < TOTAL_NUMBERS; i++) { cout << numbers[i] << " "; } cout << "\nThe largest number is " << max; cout << "\nThe occurrence count of the largest number is " << count; system("PAUSE"); return 0; } TestArray.cpp

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Example: Assigning Grades This program reads students scores, gets the best score, and then assigns grades based on the following scheme: Grade is A if score is >=best – 10; Grade is B if score is >=best – 20; Grade is C if score is >=best – 30; Grade is D if score is >=best – 40; Grade is F otherwise; AssignGrade.cpp

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved AssignGrade.cpp #include using namespace std; int main() { // Maximum number of students const int NUMBER_OF_STUDENTS = 5; int scores[NUMBER_OF_STUDENTS]; // Array scores int best = 0; // The best score char grade; // The grade // Read scores and find the best score for (int i = 0; i < NUMBER_OF_STUDENTS; i++) { cout << "Please enter a score: "; cin >> scores[i]; if (scores[i] > best) best = scores[i]; } // Assign and display grades for (int i = 0; i < NUMBER_OF_STUDENTS; i++) { if (scores[i] >= best - 10) grade = 'A'; else if (scores[i] >= best - 20) grade = 'B'; else if (scores[i] >= best - 30) grade = 'C'; else if (scores[i] >= best - 40) grade = 'D'; else grade = 'F'; cout << "Student " << i << " score is " << scores[i] << " and grade is " << grade << "\n"; } system("PAUSE"); return 0; }

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved AssignGrade.cpp // Assign and display grades for (int i = 0; i < NUMBER_OF_STUDENTS; i++) { if (scores[i] >= best - 10) grade = 'A'; else if (scores[i] >= best - 20) grade = 'B'; else if (scores[i] >= best - 30) grade = 'C'; else if (scores[i] >= best - 40) grade = 'D'; else grade = 'F'; cout << "Student " << i << " score is " << scores[i] << " and grade is " << grade << "\n"; } system("PAUSE"); return 0; }