At the end of this lesson, you will be able to:
understand and use a 2D arrays (or lists in Python)
arrays and for..each loops
from the online book Computer Based Problem Solving by Patrick Coxall, read:
we use 2D arrays to keep data as a grid or spreadsheet with rows and columns
essentially it is an array of arrays
in Python the size of the 2D array is dynamic. It expands and contracts according to the number of elements.
in C++ the size of the 2D array is fixed
Create a program called “2D Arrays” that asks the user for the number of rows and columns and then creates a 2D array of that size.
The program uses 2 loops (a loop inside a loop) to generate random numbers between 1 and 50 and display them to the user. It then places the numbers into the 2D array (a list in Python or an array in C++).
You will need the following constants in both Python and C++:
MIN_NUM = 1
MAX_NUM = 50
To declare an array in C++, use the following:
#include <array>
std::array<int, MAX_ARRAY_SIZE> arrayOfInt;
In C++, you cannot create the array dynamically like you can in Python. You will have to decide on the size of the array beforehand. Use:
const int NUM_ROWS = 5;
const int NUM_COLUMNS = 7;
We will use the following to generate a random number in C++:
#include <time.h>
srand(time(NULL));
randomNumber = (rand() % MAX_VALUE) + MIN_VALUE;
The program has a function called “cal_average()” in Python and “calcAverage()” in C++.
It accepts a 2D array as a parameter.
The function MUST use a loop to calculate the sum. Then use the following formula to calculate the average:
average = sum / number_of numbers
Remember that average can be a decimal!
Do NOT use a built-in function to calculate the average.
It returns a single variable - the min value in the array (or list).
The average will then get displayed in main().
Do NOT use a hard-coded number (i.e. 10). Use the built-in length / size() functions.
In Python, use:
len(list_of_int)
In C++, use:
#include <array>
arrayOfInt.size()
Since your data is random, it is not possible to create test cases in advance.
Instead, insert 3 test cases of your program output. Then visually check to make sure your output is correct.
Note: The top-down design should be for the entire program. There should be a flowchart for each function.
in groups of 2, do the following on the board for today's daily assignment:
Top-Down Design
Flow Chart
Pseudocode
Test Cases
complete the Daily Assignment section in Hãpara Workspace for this day
if Hãpara is not working, make a copy of this document
move it to your IMH-ICS folder for this course
recreate the same program in C++