Uploaded by enekesh

Module 13 - Many to One - Arrays v22a

advertisement
Module 13 - An array
Definition Array: Reduce MANY declarations statements to ONE declaration
statement.
When you take many and reduce it to one, it makes life easier and more enjoyable.
Think about it. Remember the CROW ! The array is a powerful concept.
As a programmer you should appreciate it when there is significantly less code to
write. JOY !
Ode to Joy: http://www.youtube.com/watch?v=xpcUxwpOQ_A
The PROBLEM:
Example: Say you need 10 individual integer variables for your program. You could write the following:
int age1 = 0;
int age2 =0 ;
int age3 = 0;
int age4 = 0;
int age5 = 0;
int age6 = 0;
int age7 = 0;
int age8 = 0;
int age9 = 0;
int age10 = 0;
You now have 10 variables of 4 bytes each. Each variable is assigned is own contiguous 4 byte block of memory.
Well, you might be thinking… “10 variables is not so bad, I can do that easily”,
Ok… now let me hit you with this thought….”Imagine you need 50,000 integer variables to store ages”.
Writing FIFTY THOUSAND declaration statements ? This is ABSOLUTE NOT practical ….. No way.
So, I pose you a question: What would you rather do….
Write 50,000 individual declaration statements, or ONE declaration statement ?
The SOLUTION:
The ARRAY…
The array is a method used to write as many variables as you need, quickly and easily.
Definition: Variable – Portion of RAM. Each variable is allocated a certain number of
bytes in RAM, depending on its data type. The byes of the variable are contiguous.
Definition: Array – Multiple variables, all of the same datatype, declared in one
statement. The bytes of the array are contiguous.
Variable Declaration Syntax:
DataType VariableName;
Array Declaration Syntax:
DataType ArrayName[# ];
// # number of elements needed
The variable declaration statement uses the datatype to determine the number of bytes needed.
char
int
float
double
- 1 byte
- 4 bytes
- 4 bytes
- 8 bytes
The array declaration statement use the number of variables[# ] multiplied by the datatype’s byte requirement to
determine the number of bytes needed. See illustration below
Make the BUCKET…
Step 1 – Declaration Statement: datatype arrayName [ # number variables ];
example:
int ages[4] ;
// Declare array of 4 integers
example:
double temps[1000] ;
// Declare array of 1000 doubles
example:
char characters[40000] ;
// Declare array 40,000 characters (slam !)
Definition: Array size – N. The number of elements in an array.
Indicated when declaring the array by the [#]
ACCESS the BUCKET - Use the index
The index is a positive integer number indicating which element (variable) in the array group you want to use.
The index always starts with zero, and goes to N-1 ( This called the offset by 1). N = size of array.
Examples:
int x[10];
size = 10. Index: 0 – 9
char c[50];
size = 50. Index: 0 – 49
string s[1000] size = 1000. Index: 0 – 999
double d[40000] size = 40,000. Index 0 – 39999
USE the BUCKET…
Step 2 - Assignment Statement: arrayName [ # ] = expression;
example: ages[0] = 42;
example: temps[10] = 72;
example: characters[25001] = ‘$’;
Video Watch ME: Arrays - http://www.youtube.com/watch?v=M4E6CDkaMds
Video Watch ME: Arrays – http://www.youtube.com/watch?v=XEzM77ICfBU
Alternative name for index: OFFSET
Definition: Offset - How far away, or the distance you are from something. Offset.
o
o
o
o
o
Zero (0) meaning you are at the start
1 mean you are one away from the start
2 mean you are two units away from the start.
….
N-1 means you are N-1 units away from the start.
Each element (variable) in the array has a size dictated by the variable datatype used in the array.
The index is a positive integer count that is the offset (number of units) from the beginning of the array.
See illustration below
Initialization of an array
Initialize means the action of placing a value in a variable for the INITIAL / FIRST time.
There are two(2) general methods to initialize an array.
1)
When you declare it
Short List Initialization – Best for arrays with a big number of elements. Only good for zero value
Uses { } squiggly braces
Example :
Example :
int ages[100] = { 0 };
double ages[1000] = { 0.0 };
// All 100 elements are initialized to zero
// All 1000 elements are initialized to zero
Long List Initialization – Good for arrays with few elements when you want to initialize each element
Uses { } squiggly braces
// All 4 elements individually initialized
Example:
int ages[4] = { 42, 69, 104, 21 };
Example: string firstNames[4] = { “Tuyet”, “Miguel”, Julie”, “Amber” };
Example:
char letters[4] = { ‘a’ , ‘$’, ‘8’, ‘P’ };
Example:
double ages[4] = { 42.1, 69.3, 104.98, 21.0 };
// integers
// strings use “ “
// char use ‘ ‘
// decimals
2)
After you declare it
Individually
Example:
int ages[4]; // Declare it first
ages[0] = 42; // Assign values next
ages[1] = 69;
ages[2] = 104;
ages[3] = 21;
All using loop
Example:
int ages[1000]; // Declare it first
for ( int i = 0 ; i < 1000 ; i++) {
ages[ i ] = 0; // Use loop to assign all to 0 value
}
Array Index Out of Bounds
Programmer Alert: Array index out of bounds
Example :
.
int ages[4] = {0};// Declare 4 element integer array, ages, and Initialize all elements to zero.
// Only positive integers 0,1,2,3 are valid indexes in a 4 element array.
OK
NOT OK
NOT OK
cout << ages[2];
cout << ages[4];
// 2 is a valid index
// 4 is NOT a valid. – Out of bounds
int ages[4] = {0};//
You use 0 to 10, when you mean
for ( int i = 0 ; i <= 10 ; i++ ) {
cout << "ages[" << i << "]: " << ages[i] << endl;
}
0 to 3.
OFF BY ONE (1) Error
Programmer Alert: If you forget the index starts with ZERO, then you are OFF by one
Example:
NOT OK
NOT OK
NOT OK
.
int ages[4] = { 0 }; // Declare 4 element integer array, ages, and Initialize all elements to zero.
// Only positive integers 0,1,2,3 are valid index
cout << ages[4];
cout << ages[1];
// You use 4 when you really mean 3 – off by 1
// You use 1 when you really mean 0
int ages[4] = {0 };//
You use 1 to 4, when you mean
for ( int i = 1 ; i <= 4 ; i++ ) {
cout << "ages[" << i << "]: " << ages[i] << endl;
}
0 to 3.
Calculation with array Elements
Declare and Initialize array:
int ages[4];
ages[0] = 42;
ages[1] = 69;
ages[2] = 104;
ages[3] = 21;
Calculation Example: Just use it like a regular variable in an Expression.
cout << ages[1] – ages[0]; // 69 – 42 is 27
ages[3] = ages[2] +10;
// adds 104 + 10 and assign 114 to ages[3]
Arrays 1 Dimensional - https://www.youtube.com/watch?v=1kLw8kZuccQ
Create an Array Using Loops - https://www.youtube.com/watch?v=Z9Wc8EsGjJY
Using Arrays in Calculations - https://www.youtube.com/watch?v=v2dKtxtWT5o
Format decimal Output
Make your output look good…
Using the <iomanip> library you can use some commands found there that let you format output.
// Place this block of code before your calculations.
cout << fixed;
cout << setprecision(0);
cout << setw(50);
// Do not show floating point numbers scientific notation.
// Number of decimal places to show
// Width of space for each answer
Example:
Video Watch Me: Format output
https://www.youtube.com/watch?v=GYaZ_FWDkk8
Two or more Dimensional Array
A one dimensional array can be visualized as a LIST
A two dimensional array can be visualized as a TABLE - with columns and rows
A three dimensional array can be visualized as a CUBE - a stack of tables
To declare a multi dimensional array you need a set of [] for each dimension.
1-Dim datatype myListArray[#]
2-Dims datatype myTableArray[#][#]
3-Dims datatype myCubeArray[#][#][#]
- one set of [#]
- two sets of [#][#]
- three sets of [#][#][#]
The index again starts at ZERO(0) for each dimension and ends at N-1.
Example:
int myArray[3][4];
0-2 for the first index
0-3 for the second index
Assign a value to individual element.
Example:
myListArray[0][0] = 42;
myCubeArray[0][0][0] = 69;
Using loops to access all elements in an array.
Example 1 – One(1) Dim
for ( int i = 0; i < 10; i++ )
{ myListArray[i] = 0; }
Example 2 – Two(2) Dims
for ( int i = 0; i < 10; i++ ) {
for ( int j = 0; j < 10; j++ )
{ myTableArray[i][j] = 0; }
}
Example 3 – Three(3) Dims
for ( int i = 0; i < 10; i++ ) {
for ( int j = 0; j < 10; j++ ) {
for ( int k = 0; k < 10; k++ )
{ myTableArray[i][j][k] = 0; }
}
}
ASSIGNMENT
Problem 1)
Write a program the uses 17 variables and an array of 17 variables.
Part 1
In this part, declare 17 individual variables, and initialize them each to 0.
Write 17 different cout and cin statements so a user can be prompted to input a number into each variable.
Write 17 cout statements that print out the content of each variable.
Part 2
After you get the above working, add to the program…
Declare a single integer array of 17 variables, and short list initialize them all to 0.
Use a loop to have the user prompted to enter a value for each variable in the array.
Use a loop to print the 17 values of the integer array.
Which method has less code, and is simpler.
Use filename: Week13YourNameProg1VarsVersArray
Problem 2)
Max size is ?
Declare an array of doubles, and initialize them all to zero.
What is the largest array your system lets you allocate, without an error ?
Try 10, then 100, then 1000, then 10000, etc.. play with it on your system tell you find the largest size.
Do you think other systems would have different sizes, why or why not ? ( Google it )
Use filename: Week13YourNameProg2MaxSize
Problem 3)
User input stored in an array…
Create an array of strings to store 6 names.
Prompt the user, using a loop, to enter 6 names, one at a time, and store them one at a time
in the names array.
Print out the names from the names array using another loop.
Use filename: Week13YourNameProg3NamesArray
Problem 4)
Run the Code for the Array out of bound error example below.
Explain what you are looking at when you go out of bounds. ( look up on internet )
int ages[5] = {0};//
You use 0 to 10, when you mean
for ( int i = 0 ; i <= 10 ; i++ ) {
cout << "ages[" << i << "]: " << ages[i] << endl;
}
0 to 3.
What types of problems could you cause if your code writes over those values outside the array ?
What types of problems could you cause if you read/use those values in your calculations ?
Use filename: Week13YourNameProg4BoundsError
Problem 5)
Run this program and explain what each line of the code does with comments.
// Programmer Explain the results
#include <iostream>
using namespace std;
#include <cmath>
#include <iomanip>
int main ()
{
int arrayIntegers[50] = {0};
int i = 0;
cout
cout
cout
cout
<<
<<
<<
<<
fixed;
setprecision(0);
setw(50);
right;
//
//
//
//
//
//
for (i = 0 ; i < 50 ; i++ ) { //
cout << " ------------------------------------------- " << endl; //
cout << " 2 ^ " << i << " = " << pow(2.0,i) << endl;;
//
arrayIntegers[i] = pow(2.0,i);
//
cout << " 2 ^ " << i << " = " << arrayIntegers[i] << endl; //
}
system ("pause"); //
return 0;
}
Use filename: Week13YourNameProg5Explain
Problem 6)
Create a two dimensional array called Multiplication table of 11 by 11 integers.
Write a for loop nested in a for loop. Calculate and assign the results of multiplying the inside and outside index
values to each element of the array.
Write a for loop nested in a for loop to print out the values that are stored in the array.
Make the outputted table lined up and looking like a multiplication table.
Use filename: Week13YourNameProg6MultTable
Problem 7)
Watch these videos first.
Buckys C++ Programming Tutorials - 36 - Multidimensional Arrays
https://www.youtube.com/watch?v=B3iC40frU4M
Buckys C++ Programming Tutorials - 37 - How to Print Out Multidimensional Arrays
https://www.youtube.com/watch?v=pAKZp_EucVg
Use filename: Week13YourNameProg7Summary
Problem 8)
Copy and Reverse Fun..
Create two arrays of strings called: ForwardNames, BackwardNames.
Initialize forwardOrderNames with: “Fred”, “Tuyet”, “Annie”, “Moe”, “Ria”, “Luke”, “Jim”, “May”, ”Rex”,
”Omar”.
Use two ‘for’ loops, to copy each element in the forwardOrderNames array into the reverse order
reverseOrderNames array in reverse order …
Print out the names in the forwardOrderNames array. 0 to 9 index show order listed above
Print out the names in the reverseOrderNames array. 0 to 9 index show reverse order listed above.
Hint: Set up a revere read the index ( 9 to 0 ) in a for loop of an array.
Use filename: Week13YourNameProg8ReverseNames
Questions 10 – Use filename: Week13yourNameQ10
1) What is an array ?
2) What are the restrictions on the datatype for each element of an array ?
3) Why use an array ?
4) What is the ‘Offset problem’ with arrays ?
5) What is short list initialization? give an example
6) What is long list initialization? give an example
7) What are Nested for loops ?
8) What are multidimensional arrays ?
9) Why are the array elements contiguous ?
10) Do you like arrays ?
© 2022 By Bill Schwarz - All rights reserved
Download