Skip to content

Instantly share code, notes, and snippets.

@natecraddock
Last active March 2, 2021 17:25
Show Gist options
  • Save natecraddock/6726723a7ac3028bb44af616960fc19a to your computer and use it in GitHub Desktop.
Save natecraddock/6726723a7ac3028bb44af616960fc19a to your computer and use it in GitHub Desktop.
// These are the functions I used for printing out the arrays
// And vectors. Maybe you will find them useful
void PrintIntVector(vector<int> vec) {
cout << "[";
for (unsigned i = 0; i < vec.size(); ++i) {
cout << vec.at(i);
if (i < vec.size() - 1) {
cout << ", ";
}
}
cout << "]\n";
}
void PrintIntArray(int arr[], int size) {
cout << "[";
for (unsigned i = 0; i < size; ++i) {
cout << arr[i];
if (i < size - 1) {
cout << ", ";
}
}
cout << "]\n";
}
#include <iostream>
using namespace std;
int RandIntInRange(int min, int max) {
return rand() % (max - min + 1) + min;
}
int main(){
// We use srand(5) to ensure the pattern of random numbers is the same
// each time the program is run. This is so the zyBooks autograder can
// accurately grade a consistent output. In a real program this would
// more likely be srand(time(0))
srand(5);
const int ARRAY_SIZE = 5;
// Create 2D array of ARRAY_SIZE x ARRAY_SIZE
// Arrays created without instantiation = {...}
// are filled with unknown "junk" data.
int array[ARRAY_SIZE][ARRAY_SIZE];
// Fill with random numbers
// Iterate over rows
for (int row = 0; row < ARRAY_SIZE; ++row) {
// Iterate over each column in the row
for (int col = 0; col < ARRAY_SIZE; ++col) {
// At this row,column set that value in the array to a
// random number between 10 and 50 inclusive.
array[row][col] = RandIntInRange(10, 50);
}
}
// Print out numbers
for (int row = 0; row < ARRAY_SIZE; ++row) {
for (int col = 0; col < ARRAY_SIZE; ++col) {
cout << array[row][col] << " ";
}
cout << endl;
}
// Sum the numbers
int sum = 0;
for (int row = 0; row < ARRAY_SIZE; ++row) {
for (int col = 0; col < ARRAY_SIZE; ++col) {
sum += array[row][col];
}
}
cout << "The sum of all the values is: " << sum << endl;
// This could be done in a single nested for loop, but I
// split it into three for clarity.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment