1 of 25

INTRO TO ARRAYS

A LECTURE FOR THE C++ COURSE

Each slide may have its own narration in an audio file. �For the explanation of any slide, click on the audio icon to start the narration.

The Professor‘s C++Course by Linda W. Friedman is licensed under a �Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

2 of 25

WHAT IS AN ARRAY?

An array is a finite set of ordered, homogeneous elements.

  • Finite – a specific number of elements in the array
  • Ordered – elements are arranged so there is a first, second, etc.
  • Homogeneous – all elements must be of the same data type

RECURSION

2

3 of 25

WHEN DO WE NEED ONE?

Arrays are used when it is necessary to

  • keep a large number of items in memory at the same time

and to

  • to perform some operation(s) on them in a uniform manner.

RECURSION

3

4 of 25

WHAT DO WE DO WITH IT?

Some basic array operations:

  • Declaration of the array
  • Retrieval of a given element value from the array (uses subscript)
  • Storing a value in a given position in the array
  • Searching for a target element
  • Sorting the array

RECURSION

4

5 of 25

TO DECLARE AN ARRAY IN C++

int X [100];

Just like any other declaration:

      • An array must be declared fully before it is used in the program.
      • None of the descriptive information in the definition of the structure changes in any way during the lifetime of the structure.

RECURSION

5

6 of 25

ACCESSING ELEMENTS IN AN ARRAY

Array elements are stored sequentially in memory. They all have the same variable name, and are referred to individually by means of subscripts in brackets, e.g.:

X[3] = 24.6;

X[2] = 4 * A + 13;

 

In this case, X is a one-dimensional array.

RECURSION

6

7 of 25

EXERCISE:

RECURSION

7

What is the value of each of the following?

 

Y[0] _______ Y[1] _______ X[0] _______

A _______ Y[B] _______ Z[A] _______

B _______ Y[C] _______ Z[B] _______

Y[A] ______ X[A] _______ Y[A+2] ________

GIVEN

DO

8 of 25

TBD

RECURSION

8

9 of 25

TO ACCESS ARRAY ELEMENTS

To access array elements we use the for loop.

RECURSION

9

10 of 25

PROBLEM: ARRAY I/O

RECURSION

10

How to do this?

Program Output:

11 of 25

PROBLEM: ARRAY I/O

//array1.cp

#include <iostream>

using namespace std;

int main(){

double a[4];

cout << "Enter 4 real numbers: \n";

for (int i=0; i<4; i++){

cout << i+1 << ": ";

cin >> a [i];

}//end for

cout<< "\nEnd of data entry.\n \n";

cout << "Here's what the array looks like: \n";

for (int i=0; i<4; i++){

cout << "a["<<i<<"]= " << a[i] << endl;}

return 0;

}//end main

RECURSION

11

HERE’S HOW!!

12 of 25

PROBLEM: ARRAY I/O

//array2.cp

#include <iostream>

using namespace std;

int main(){

const int SIZE = 4;

double a[SIZE];

cout << "Enter 4 real numbers: \n";

for (int i=0; i<SIZE; i++){

cout << i+1 << ": ";

cin >> a [i];

}//end for

cout<< "\nEnd of data entry.\n \n";

cout << "Here's what the array looks like: \n";

for (int i=0; i<SIZE; i++){

cout << "a["<<i<<"]= " << a[i] << endl;}

return 0;

}//end main

RECURSION

12

THIS WORKS TOO

13 of 25

PROBLEM: ARRAY I/O

//array3.cp

#include <iostream>

using namespace std;

int main(){

const int SIZE = 4;

double a[SIZE];

cout << "Enter 4 real numbers: \n";

for (int i=0; i<SIZE; i++){

cout << i+1 << ": ";

cin >> a [i];

}//end for

cout<< "\nEnd of data entry.\n \n";

cout << "Display the array elements in reverse: \n";

for (int i=SIZE-1; i>=0; i--){

cout << "a["<<i<<"]= " << a[i] << endl;}

return 0;

}//end main

RECURSION

13

REVERSING ARRAY PROCESSING

14 of 25

PROBLEM: MINIMUM VALUE IN ARRAY

  • Write an algorithm to find the minimum value in an array of integers

RECURSION

14

15 of 25

PROBLEM: MINIMUM VALUE IN ARRAY

  • Solution #1

min = 9999; // or initialized to some other large number

for (j=0; j<SIZE; j++)

if (x[j] < min) min = x[j];

RECURSION

15

16 of 25

PROBLEM: MINIMUM VALUE IN ARRAY

  • Solution #2

min = x[0]; // min initialized to first array element

for (j=1; j<SIZE; j++)

if (x[j] < min) min = x[j];

RECURSION

16

17 of 25

PROBLEM: MINIMUM VALUE IN ARRAY

  • Solution #3

min = x[0]; // min initialized to first array element

for (j=1; j<SIZE; j++) //start comparing at x[1]

if (x[j] < min) min = x[j];

RECURSION

17

18 of 25

PROBLEM: MINIMUM VALUE IN ARRAY

  • Solution #4

min = 1; // what is min?

for (j=1; j<SIZE; j++)

if (x[j] < x[min]) min = j;

RECURSION

18

min tells WHERE, not WHAT the minimum is

19 of 25

THE VERY GRADING PROBLEM

  • Discuss: How can we use arrays is this HW program?

RECURSION

19

20 of 25

PROBLEM: COUNTING THE VOTES

Write a program to count the votes in a local community election.

The candidates: Sam Smoothe and Gaby Gruff

We will use an integer array of 2 cells to accumulate the votes.

RECURSION

20

while (v>=0)

if (v==1) votes[1]++

else if (v==2) … … …

How about this?

21 of 25

PROBLEM: COUNTING THE VOTES

//votecounter.cpp

#include <iostream>

using namespace std;

int main(){

short v;

int votes[2] = {0};

cout << "Enter a 0 for Sam Smoothe OR a 1 for Gabby Gruff.\n"

<< "When you have no more votes to enter, "

<< "type a negative number.\n\n"

<< "Enter 0 or 1: ";

cin >> v;

while (v >= 0) {

votes[v]++;

cout << "Enter 0 or 1: ";

cin >> v;

}//end while

cout << "\nSam Smoothe got " << votes[0] << " votes\n";

cout << "Gabby Gruff got " << votes[1] << " votes\n";

return 0;

}//end main

RECURSION

21

Does this work?

Try it!

22 of 25

PROBLEM: FREQUENCIES

Can we use the vote counting idea to count random integers?

We could use an integer array with 10 cells, or frequencies for the integers 0-9.

Here’s the assignment:

  1. First write the program with user input. Have the user enter digits at “random” from the keyboard, and write the program to count each one as it is entered. By the end you should have the count of the 0’s, the count of the 1’s, etc.
  2. Instead of user input, get some “real” randomness in there using the C++ rand() function (in the cstdlib library).

RECURSION

22

23 of 25

ARRAYS AND FUNCTIONS

  • When an array is passed to a function, only the name and type of the array is passed.
  • The name of a variable is equivalent to a storage location, so the effect is that the array is passed by reference even if it looks like it's being passed by value (no '&’).

Example on next slide 🡪

RECURSION

23

24 of 25

ARRAYS AND FUNCTIONS

//morearray.cpp

//Reads an array of data values, prints it, and sums the values.

#include <iostream>

using namespace std;

const int SIZE = 20;

void readarray (float[], int&);

void printarray (const float[], int);

float sumarray (const float[], int);

//**************************************

int main(){

int n;

float data [SIZE] = {0.0};

readarray(data, n);

printarray(data, n);

cout << "The sum is "

<< sumarray(data, n);

return 0;

}

//**************************************

RECURSION

24

void readarray(float x[], int &n){

n = 0; // "number of numbers" in the array

char more='y';

while (more != 'n' && more != 'N'){

cout << "\nEnter a number: "; cin >> x[n];

n++;

cout << "Another number? (y or n) ";

cin >> more;

}

}

//*********************************************

float sumarray (const float x[], int n){

float sum = 0;

for (int i=0; i<n; i++) sum += x[i];

return sum;

}

//*********************************************

void printarray (const float x[], int n){

cout << "The data values are:\n";

for (int i=0; i<n; i++) cout << '\t' << x[i];

cout << endl;

}

25 of 25

REVIEW

RECURSION

25

What did we learn in this lecture? Plenty. Some terms to jog your memory:

    • Array
    • Declaring an array
    • Processing an array using a for loop