Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.

Slides:



Advertisements
Similar presentations
1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
Advertisements

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.,
Simple Arrays COMP104 Lecture 11 / Slide 2 Arrays * An array is a collection of data elements that are of the same type (e.g., a collection of integers,characters,
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.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 8 Multidimensional.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Multiple-Subscripted Array
Chapter 9: Arrays and Strings
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 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Arrays (Part II). Two- and Multidimensional Arrays Two-dimensional array: collection of a fixed number of components (of the same type) arranged in two.
Lesson 7 Arrays CS 1 Lesson 7 -- John Cole1. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored.
Simple Arrays Programming COMP104 Lecture 12 / Slide 2 Arrays l An array is a collection of data elements that are of the same type (e.g., a collection.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Chapter 8 Arrays and Strings
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
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.
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)
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.
Lecture: Arrays. 7.1 Arrays Hold Multiple Values.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 6 Arrays.
1 Chapter 7 Arrays. 2 Topics 7.1 Arrays Hold Multiple Values 7.2 Accessing Array Elements 7.3 No Bounds Checking in C Array Initialization 7.5 Processing.
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.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 8 Arrays.
1 Arrays and Strings Lecture: Design Problem l Consider a program to calculate class average Why?? ?
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 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.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 7 Arrays.
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.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Arrays.
Chapter 7 Arrays Csc 125 Introduction to C++. Topics Arrays Hold Multiple Values Array Operations Arrays as function arguments Two-dimensional arrays.
Arrays Chapter 7. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations.
Module 1: Array ITEI222 - Advance Programming Language.
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.
C++ Array 1. C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used.
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.
Arrays. C++ Style Data Structures: Arrays(1) An ordered set (sequence) with a fixed number of elements, all of the same type, where the basic operation.
ARRAYS (C) KHAERONI, M.SI. OVERVIEW Introduction to Arrays Arrays in Functions Programming with Arrays Multidimensional Arrays.
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.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Data Storage So far variables have been able to store only one value at a time. What do you do if you have many similar values that all need to be stored?
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 An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Computer Programming BCT 1113
Chapter 6 Arrays DDC 2133 Programming II.
Chapter 6 Arrays Lecturer: Mrs Rohani Hassan
New Structure Recall “average.cpp” program
EKT150 : Computer Programming
Multidimensional Arrays
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Arrays Arrays A few types Structures of related data items
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
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:

Section 5 - Arrays

Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented by an array construct.

Array is a group of variables - Same name and data type - Variables are related in some way - Most commonly used – multi-dimensional - One-dimensional array - Two-dimensional array

Arrays Arrays allow you to store a number of similar type items but with a single name. Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations Declared using [] operator: int tests[5]; This creates an array named tests with 5 elements (storage locations)

Array Terminology In the definition int tests[5]; int is the data type of the array elements tests is the name of the array 5, in [5], is the size declarator. It shows the number of elements in the array.

Array Declaration element-type array-name [array-size]; Type of all the values in the array Name of the entire collection of values Integer expression indicating number of elements in the array

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

Suppose const int N = 20; const int M = 40; const int MaxStringSize = 80; const int MaxListSize = 1000; Then the following are all valid array definitions int A[10]; // array of 10 ints char B[MaxStringSize]; // array of 80 chars double C[M*N]; // array of 800 floats int Values[MaxListSize]; // array of 1000 ints

Array - Memory Layout The definition: int tests[5]; // size is 5 elements allocates the following memory: first element second element third element fourth element fifth element

Accessing Array Elements Each array element has a subscript, used to access the element. Subscripts start at Subscripts

Array Subscripts Enclosed in brackets ([ ]) Indicates which element is referenced by position Array subscript value is different than array element value Subscript can be an expression of any integer type To be valid, subscript must be a value between 0 and one less than the array size

Accessing Array Elements Array elements can be used as regular variables: tests[0] = 79; cout << tests[0]; cin >> tests[1]; tests[4] = tests[0] + tests[1]; Arrays must be accessed via individual elements: cout << tests; // not legal

Accessing Array Contents Can access element with constant subscript: cout << tests[3] << endl; Can use integer expression as subscript: for (i = 0; i < 5; i++) cout << tests[i] << endl;

Suppose int A[10]; // array of 10 int A[0], … A[9] To access individual element must apply a subscript to list name A A subscript is a bracketed expression also known as the index First element of list has index 0 A[0] Second element of list has index 1, and so on A[1] Last element has an index one less than the size of the list A[9] Incorrect indexing is a common error A[10] // does not exist

Array Initialization List of initial values enclosed in braces ({ }) following assignment operator (=) Values from initialization list are assigned in order to array elements Length of initialization list cannot exceed size of the array Size of array can be automatically set to number of initializing values using empty brackets ([ ])

Initialization element-type array-name [array-size] = {initialization-list}; float x[8] = {16.0, 12.0, 6.0, 8.0, 2.5, 12.0, 14.0, -54.5};

cout << x[0]; x[3] = 25.0; sum = x[0] + x[1]; sum += x[2]; x[3] += 1.0; x[2] = x[0] + x[1];

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;

C++ allows you to omit the array size when declaring and creating an array using an initializer. For example, the following declaration is valid double myList[] = {1.9, 2.9, 3.4, 3.5}; C++ automatically figures out how many elements are in the array.

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 “unkowns”, like all other local variables. double myList[4] = {1.9, 2.9};

Access to Array Elements Random Access –Access elements is any order Sequential Access –Process elements in sequential order starting with the first

Example of Sequential Access int cube[10]; for (int i = 0; i < 10; i++) cube[i] = i * i * i;

Displaying an Array // List A of n elements has already been set for (int i = 0; i < n; ++i) { cout << A[i] << " "; } cout << endl;

Finding the smallest index of the largest element double max = myList[0]; int indexOfMax = 0; for (int i = 1; i < ARRAY_SIZE; i++) { if (myList[i] > max) { max = myList[i]; indexOfMax = i; }

#include using namespace std; int main() { const int NUMBER_OF_ELEMENTS = 10; double numbers[NUMBER_OF_ELEMENTS]; double sum = 0; for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) { cout << "Enter a new number: "; cin >> numbers[i]; sum += numbers[i]; } double average = sum / NUMBER_OF_ELEMENTS; int count = 0; // The number of elements above average for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) if (numbers[i] > average) count++; cout << "Average is " << average << endl; cout << "Number of elements above the average " << count << endl; return 0; } Example

Multidimensional Arrays Allows for complex arrangement of data Can have many dimensions Syntax element-type arrayName [size 1 ] [size 2 ]…[size n ]; Example double table[NROWS] [NCOLS];

Declaring Two- Dimensional Arrays Most common multidimensional array Represents a table Example char ticTacToe[3][3]; Access ticTacToe[1][2] Row Column

Function sumMatrix float sumMatrix (float table[NROWS][NCOLS]) { float sum = 0.0; // Add each array element value to sum. for (int r = 0; r < NROWS; r++) for (int c = 0; c < NCOLS; c++) sum += table[r][c]; return sum; }

Example - A classroom seating plan

Example const int NUM_ROWS = 11; const int SEATS_IN_ROW = 9; string seatPlan [NUM_ROWS][SEATS_IN_ROW];... seatPlan[0][8] = “Gerry”;

Initialization Each inner pair of braces contains initial values for one row of the array matrix const int NUM_ROWS = 2; const int NUM_COLS = 3; float matrix[NUM_ROWS][NUM_COLS] ={{5.0, 4.5, 3.0}, {-16.0, -5.9, 0.0}};

Two-dimensional Array Illustration

Nested Loops for 2-D Arrays Row order –use row subscript as outer loop control variable Column order –use column subscript as outer loop control variable

Initializing Arrays with Random Values The following loop initializes the array with random values between 0 and 99: for (int row = 0; row < rowSize; row++) { for (int column = 0; column < columnSize; column++) { matrix[row][column] = rand() % 100; }

Printing Arrays To print a two-dimensional array, you have to print each element in the array using a loop like the following: for (int row = 0; row < rowSize; row++) { for (int column = 0; column < columnSize; column++) { cout << matrix[row][column] << " "; } cout << endl; }

Summing Elements by Column For each column, use a variable named total to store its sum. Add each element in the column to total using a loop like this: for (int column = 0; column < columnSize; column++) { int total = 0; for (int row = 0; row < rowSize; row++) total += matrix[row][column]; cout << "Sum for column " << column << " is " << total << endl; }

No Bounds Checking in C++ C++ does not check if an array subscript is in the range of values for subscripts of the array Can access memory using subscripts that is before or after the memory for an array Can corrupt other memory locations, crash program, or lock up computer Need to be careful!