Write 2 C++ Programs

profilegina123
assignment12.pptx

Arrays

Random Numbers

Arrays

Arrays are data structures consisting of data all of the same type

Arrays are laid out in memory in contiguous locations

The first element of the array is at index = 0; the last element is at index = length of the array − 1

Example:

int c[12]; // array called c has 12 integer elements

Arrays

Arrays

In C++ arrays should be initialized before use! Array processing is usually by means of a for loop:

Example:

for (int i = 0; i < 12; i++) c[i] = 0;

CAUTION: using an index < 0 or >= the array length is a runtime error!

Arrays

Arrays can be initialized by:

Prompting the user for each element (use a for loop)

From an input file (use a for loop)

IN your source code, example:

int nArray [ ] = {5, 2, 4, 1, 3};

The compiler can count, and will initialize the nArray with 5 elements

©1992-2012 by Pearson Education, Inc. All Rights Reserved.

6

Multidimensional Arrays

Random Numbers

Use srand() to seed the pseudorandom sequence; then use rand() to get the next pseudorandom number:

#include <cstdlib>

#include <ctime>

...

srand(time(NULL)); // seeds the sequence

...

roll1 = rand( ) % 6 + 1; // yields numbers between

// 1 and 6