91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Kernighan/Ritchie: Kelley/Pohl:
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
 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.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Computer Science 1620 Strings. Programs are often called upon to store and manipulate text word processors chat databases webpages etc.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
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
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction Structures are somewhat like an array in that.
 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
COIT29222 Structured Programming Slide 1 COIT29222-Structured Programming Lecture Week 06  Reading: Study Guide Book 2, Modules 9 & 10 Textbook (4 th.
(continue) © by Pearson Education, Inc. All Rights Reserved.
Palindromes revisited Here's a simpler program for checking palindromes: int nums[100]; int i = 0, a; cin >> a; while(a > 0) { nums[i++] = a; cin >> a;
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
Data Structures & Algorithms
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 If’s – The Basic Idea “Program” for hubby: take out garbage.
Pointers *, &, array similarities, functions, sizeof.
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.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Lecture 2 Functions. Functions in C++ long factorial(int n) The return type is long. That means the function will return a long integer to the calling.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Sahar Mosleh California State University San MarcosPage 1 One Dimensional Arrays: Structured data types.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
© Janice Regan, CMPT 128, January CMPT 128: Introduction to Computing Science for Engineering Students Introduction to Arrays.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Gator Engineering Google Code Jam 2015 Copyright © 2008 W. W. Norton & Company. All rights reserved. 1.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Introduction Programs which manipulate character data don’t usually just deal with single characters, but instead with collections of them (e.g. words,
Computer Programming BCT 1113
Student Book An Introduction
Arrays, For loop While loop Do while loop
One-Dimensional Array Introduction Lesson xx
C Arrays.
7 Arrays.
Arrays Kingdom of Saudi Arabia
7 Arrays.
Suggested self-checks: Section 7.11 #1-11
Arrays Arrays A few types Structures of related data items
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes (storage cells). double a /* scalar */, b [6] /* array */; int c[4] /* array */; bool f[3] /* array */, g /* scalar */; double bool int double bool a b c f g Arrays are declared in the same way as the “scalar” variables we’re used to, and array and scalar declarations may be intermingled as shown above. Arrays of length 1 and scalars are NOT equivalent, though they may look so in the diagram above.

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 2 Initializing Arrays Array variables may be given initial values, int z[4] = { 3, 2, 4, 6 }; 3246 z ‘a’‘b’‘c’ s char s[3] = { ‘a’, ‘b’, ‘c’ }; When an initial value is specified, the array size may be omitted (the compiler can count). Thus: int z[] = { 3, 2, 4, 6 }; // same as above Character arrays are not usually initialized as shown above. Instread “string” constants are usually used (more on this later).

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 3 Array No-no’s Assume int a[6], b[6]; Arrays cannot be read (except for char arrays): cin >> a; // Illegal!! Arrays cannot be written (except for char arrays): cout << a: // Illegal!! Arrays cannot be assigned: a = b; // Illegal!! a = { 1, 2, 6, 3, 6, 6 }; // Illegal (only OK in declarations)!! Arrays cannot be compared: if (a != b) { // Illegal!! Arrays cannot be added, etc.: a = a + b; // Illegal!!

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 4 Array Element Selection (1) The individual elements of an array are numbered, starting with element zero, and may be selected using the […] operator. int z[4] = { 3, 2, 4, 6 }; 3246 z z[0]z[1]z[2]z[3] The “…” represents an integer expression. If an array has “n” elements, the expression should evaluate to a value between 0 and “n-1” inclusive, but there is essentially no protection against the inadvertent use of invalid “index” values. int a = 3, b = 2; z[a] = z[b]; // OK - z[3] gets z[2] z[a + b] = 0; // oops! z[a - b] = 0; // OK - z[1] gets zero z[((b * 2) + a) - 5] = 1; // OK - the expression can be // complex as we want

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 5 Array Element Selection (2) Once an array element has been selected, it can be used in all the ways that a scalar variable of the same type can be. If we have an array of int’s, for example, selected elements may be used wherever an int variable if permissable. int a[6], b[6], c, d;... cin >> a[3]; if (a[2] != b[3]) { cout << a[c]; b[d + 2]++; } a[b[3]] = 6; In particular, array elements may be passed “by reference”. void func (int &x) { // assume defined somewhere…... } func (a[2]); // OK

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 6 First Array Example (1) Problem: Program is to read in up to 10 values (terminated with a -1, not to be included in the 10) and write them out in reverse order. #include … void main (void) { int array[10], // space for values read count, // number of values read i, value; // read values into array // write out values in reverse order } // end main

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 7 First Array Example (2) // read values into array count = 0; // nothing read so far cout << “Enter up to 10 values…\n”; cin >> value; // read in first value // loop while we haven’t seen the terminating // value (-1) and the array isn’t full while ((value != -1) && (count < 10)) { array[count++] = value; // store value cin >> value; // and read another one } // if things are going well, “value” should contain -1 at // this point. if it doesn’t, we must have stopped looping // because the array was full (too many values were entered) if (value != -1) { cout << “Too many values entered.\n”; return; } // “count” now contains the number of values read. // this value may be zero (-1 entered immediately)

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 8 First Array Example (3) // write out values in reverse order cout << “The values are:\n”; for (i = count - 1; i >= 0; i--) { cout << array[i] << endl; } This code will work correctly even if no values are entered. If you find the for loop confusing, replace it with the equivalent while loop. i = count - 1; while (i >= 0) { cout << array[i] << endl; i--; } To output the values in their original order: cout << “The values are:\n”; for (i = 0; i < count; i++) { cout << array[i] << endl; }

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 9 First Array Example (4) This example program is flawed in that it involves two “magic numbers” - 10 (the maximum number of values) and -1 (the special terminating value). It would be much better if it were modified as shown below: void main (void) { const int max_values = 10, terminator = -1; int array [max_values] …... cout << “Enter up to “ << max_values << “ values … while ((value != terminator) && (count != max_values)) { … if (count == max_values) { … Expressions may be used in defining arrays provided that they evaluate to a constant value.

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 10 Bubble Sort (1) A bubble sort involves making one or more “passes” over the data to be sorted. On each pass the first value is compared to the second, the second to the third, and so on. If the two values compared are out of order, they are swapped (interchanged). To sort: Continue making passes over the data until we have a pass on which no swaps occur. The data is now sorted. A refinement: Make each pass one comparison shorter (after the first pass the largest value will have “bubbled” to the last position, and we need only worry about the preceding values). = compare and swap if necessary

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 11 Bubble Sort (2) const int max_vals = 100; int array[max_vals], count, i, temp, stop; bool swap_occurred; // on the first pass, we must compare all pairs stop = count - 1; // count = number of values do { // we haven’t had any swaps so far on this pass swap_occurred = false; for (i = 0; i < stop; i++) { if (array[i] > array[i + 1]) { // values are out of order temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; swap_occurred = true; } // the next pass should do one less comparison stop--; } while (swap_occurred);

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 12 Selection Sort (1) In a selection sort, we begin by comparing the first array element with each of the following elements (with values getting interchanged when they are out of order). Then we compare the second array element with each of the following elements, and so on, until we have compared the second last element with each of the following elements (e.g with to the last element). first pass: compare the first element to all following elements second pass: compare the second element to all following elements last pass: compare the second last element to the last element

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 13 Selection Sort (2) const int max_vals = 100; int array[max_vals], count, i, j, temp; // assume that "count" contains the number // of values stored in the array (the number of // values to be sorted) // sort array for (i = 0; i < (count - 1); i++) { for (j = i + 1; j < count; j++) { if (array[i] > array[j]) { // values are out of order temp = array[i]; array[i] = array[j]; array[j] = temp; }

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 14 Arrays as Function Parameters (1) Arrays can be passed to functions (e.g. an array declared in one function can be made available to other functions). This is always done “by reference”, but there is no ‘&’ in the parameter declaration. Instead call by reference is implied by the fact that we’re dealing with an array. void func (int a, int &b, int c[]) {... } call by value call by reference call by reference (array case) “a” is an integer variable. the calling function must supply a value, and “a” is initialized with this value. “b” is a reference to an integer variable. the calling function must supply an integer variable, and “b” is initialized by being made to refer to this variable. “c” is a reference to an array of integers. the calling function must supply an integer array (of any length), and “c” is initialized by being made to refer to this array.

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 15 Arrays as Function Parameters (2) void func (int a, int &b, int c[]) {... } void main (void) { int x, y[6], z = 3;... func (z * 4, x, y); … } 3 12 a b c x y z Every operation upon “c” will apply to “y”. If the functions outputs c[0], the value in y[0] will get displayed, and so on.

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 16 Array Parameter Example (1) No length is normally specified in declaring an array parameter, and any length of array may be supplied by the calling function. This is very useful, but does require that we somehow let the called function know how many array elements are to be processed. This is normally done by passing the number of elements separately, as in the example below. void write_array (int n, int array[]) { int i; for (i = 0; i < n; i++) { cout << array[i] << endl; } This function prints out the first “n” elements of the array passed to it. This may or may not be the entire array (the function neither knows or cares).

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 17 Array Parameter Example (2) void main (void) { int m[50], s[12];... cout << “The elements of m are:\n”; write_array (50, m); // output all of array m cout << “The elements of a are:\n”; write_array (12, s); //output all of array s cout << “The first ten elements of m are:\n”; write_array (10, m); // OK... write_array (100, m); // Oops - an error!!... } While it is OK to have “write_array” output only the first part of an array, it is an error to try and output more elements than there actually are. Such errors will not be detected by the compiler and can be tricky to track down. Modifying “non-existant” array elements can, and normally will, result in very peculiar program behaviour.

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 18 Array Input Function // reads a list of of up to "max_values" values (terminated by // -1) into "array". sets "actual_values" to the number of // values actually read (possibly zero). returns true if the // complete list of values entered was sucessfully processed // and false otherwise (too many values entered). bool read_array (int max_values, int array [] int &actual_values) { int value; actual_values = 0; // nothing read in so far for (;;) { cin >> value; if (value == -1) { // input is complete return true; } if (actual_values == max_values) { // the user has entered too many values return false; } // store the value in the array and increment our counter array[actual_values++] = value; } // end for (;;) // no return required because we can't get here }

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 19 Bubble Sort Function // sorts array in ascending order void bubble_sort (int n /* array size */, int array[]) { int stop, temp, i; bool swap_occurred; stop = n - 1; // the first pass goes all the way do { swap_occurred = false; // no swaps so far this pass for (i = 0; i < stop; i++) { if (array[i] > array[i + 1]) { // values are out of order temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; swap_occurred = true; } stop--; // stop one place shorter next time around } while (swap_occurred); }

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 20 Sample Main Function void main (void) { const int max_vals = 100; int array[max_vals], count; // read in a list of values cout << "Enter a list of values (terminated by -1).\n: "; if (!read_array (max_vals, array, count)) { cout << "Array read failed (too many values).\n"; pause (); return; } // "count" now contains the number of values read // sort the array bubble_sort (count, array); // output the array cout << "The values in ascending order are\n"; write_array (count, array); pause (); }

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 21 Rainfall Example (1) Problem: We have a collection of of rainfall readings and want to output the number of days for which the rainfall is: from 0 to mm from 5 to mm... from 40 to mm 45 and over mm 10 categories in total To solve this problem, we will make use of an array of ten counters (one for each category). The program will begin by setting all of these counters to zero. This is easier than specifying an initial value for the array, and more adaptable (what if we decide we want 100 categories?). int counters [10]; // one per category int i; double rainfall; for (i = 0; i < 10; i++) { counters[i] = 0; }

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 22 Rainfall Example (2) Next we loop, obtaining and processing readings. for (;;) { // obtain next reading and store in “rainfall”. // break out of loop if at the end of the data.... // compute counter array index and // increment the corresponding counter i = (int) (rainfall / 5); if (i > 9) { i = 9; } counters[i]++; // counters[i] = counters[i] + 1 } // end for (;;) // “counters” now contains the desired values See sample program rainfall.cpp.