Filling a Two Dimensional array with random numbers in C++ - c++

I am making a program that inserts a two dimensional array with random integers and locates the highest value to display it and it's coordinates in the array. I am using three files. utils.h, utils.cpp, and main.cpp. My program displays an array but it is not correct and I cannot figure out why despite all my research. Any help would be appreciated. This is a college assignment and I know that my professor wants main and utils.h left as is so the only thing I can change is utils.cpp. Thank you for your time.
#include "utils.h"
void fillTable(int table[ROW_COL_SIZE][ROW_COL_SIZE]) {
for(int i = 0; i < ROW_COL_SIZE; i++) {
for(int c = 0; c < ROW_COL_SIZE; c++) {
cout << rand() % table[i][c];
}
}
}
void findLargest(int table[ROW_COL_SIZE][ROW_COL_SIZE], int& largestRow,
int& largestCol) {
largestRow = 0;
largestCol = 0;
for ( int i = 0; i < ROW_COL_SIZE; i++) {
for ( int j = 0; j < ROW_COL_SIZE; j++) {
if(table[i][j] > table[largestRow][largestCol]) {
largestRow = i;
largestCol = j;
}
}
}
}
void displayTable(int table[ROW_COL_SIZE][ROW_COL_SIZE]) {
for (int i = 0; i < 10; i++) {
for ( int j = 0; j < 10; j++) {
cout << table[i][j];
}
}
}
This is my output I am getting.
55302337713078127332504421405961229072248303443307961481223132483391855019110600
92808812679236602328231529150663269913935376911094217591887215022974011255316512
71103276228950168692675422850260269511370054042617128509148242205517590190271332
93168530667935211606208729747118402681321223203422069312038223266476231187148148
05966618422064721159313592422312213211891498452701498229001417726265175102184575
4298481247015001631326472115171254718059341323252489617888241851323216308-858993
460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993
460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993
460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993
460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993
460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993
460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993
460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993
460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993
460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993
460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993
460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993
460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993
460-858993460-858993460-858993460The largest value located at [0] [0] is: -85899
3460
Press any key to continue . . .

Should fillTable fill table? Currently it does not - it only prints to cout. Therefore, table appears to remain uninitialized.
So, in fillTable, instead of:
cout << rand() % table[i][c];
You probably want something like:
table[i][c] = rand();

In fillTable you should use something like:
table[i][c] = rand() % MAX_VALUE; // MAX_VALUE is the largest value +1 you want to generate
cout << table[i][c] << " ";
(Note the whitespace to separate numbers, you might also want to insert a cout << endl; after each row. But I'm not sure if fillTable should also print out the values?)
Also the displayTable function only prints the first ten lines/columns (but this might be intentional?)

You are just making the random number output and not inserting in it.
do it like this
table [i][c] = rand () % table [i][c] ;
PLus you are getting a garbage value when you find the largest value because there is no actual value stored in the array.

Related

Is there a way to count the number of ocurrences of each element of a string array?

I have the following code that does exactly what I want. The problem is that I need the sample array to compare the strings and keep the count. Is there a way to count the number of occurrences of each string on any array without a sample?
For a little bit more context, the initial problem was to read data from a .txt file including vehicles information, like:
Volkswagen Jetta
Ford Focus
Volkswagen Jetta
And count the number of vehicles of each brand. Keep in mind that this is from an introductory course for programming, and we don't know how to use vectors or maps.
#include <iostream>
#include <string>
using namespace std;
using std::string;
#define MAX 20
int main(){
int counter[MAX];
string arr[MAX]={"ABC","AOE","ADC","ABC","ADC","ADC"};
string sample[MAX]={"ABC", "AOE", "ADC"};
for(int i=0; i<=MAX; i++){
counter[i]=0;
}
for(int i=0; i<MAX;i++){
for(int j=0; j<MAX; j++){
if (sample[i]==arr[j]){
counter[i]++;
}
}
}
for(int i=0; i<3;i++){
cout<< sample[i] << "=" << counter[i]<<endl;
}
return 0;
}
All you are expected to do is keep a list (an array will do) of brand names, and an array of counts for each name:
std::string brand_names[100];
int counts[100]; // number of times each element of brand_names[] was read from file
int num_items = 0;
Each time you read a brand name from file, try to find it in the array of strings. If found, just add one to the count at the same index. If not found, add it to the end of the brand_names[] array, add 1 to the end of the counts[] array, and increment num_items.
You do not need anything more than a simple loop for this:
an outer loop to read the next brand name from file
an inner loop to try to find the brand name in the list
If you want to solve this problem without knowing the initial values of the sample array:
Create an empty sample array. When you see new elements add them to this array.
Use a variable sample_size to keep track how many samples have been seen. Below is a simple example which doesn't use std::vector or dynamic allocation.
int main()
{
std::string arr[MAX] = { "ABC","AOE","ADC","ABC","ADC","ADC" };
std::string sample[MAX];
int sample_size = 0;
int counter[MAX] = { 0 };
for (int i = 0; i < MAX; i++)
{
if (arr[i].empty()) break;
bool sample_found = false;
for (int j = 0; j < sample_size; j++)
if (arr[i] == sample[j])
{
sample_found = true;
counter[j]++;
break;
}
if (!sample_found)
{
sample[sample_size] = arr[i];
counter[sample_size]++;
sample_size++;
}
}
for (int i = 0; i < sample_size; i++)
cout << sample[i] << "=" << counter[i] << std::endl;
return 0;
}

Looking for solution to array and cout interaction in C++

I want a function or loop to run through the array and print each element out until it has printed 10 elements. In which case, a new line is started and the printing continues. eg. 1 2 3 4 5
6 7 8 9 10
This is for a program that works an array like a 50's housewife performing many calculations and alterations to said array.
This is my current attack on the logic behind my issue.
int main()
{
test = new int[100];
for (int i = 0; i < 100; i++){
//Set array to rand
test[i] = rand() % 44 + 55;
}
printf("original List\n");
for (int i = 0; i < 100; i++){
// print original order
printf("%d\n", test[i]);
}
sortArr;
// function call sort array ascend
printf("\Sorted List\n");
for (int i = 0;i < 100;i++) {
// print sorted order
printf("%d , ", test[i]);
int temp;
//temp counter for width of printout
for (temp = 0;temp < 10;temp++) cout<< "\n" << endl;
sum += test[i];
}
Expected is a block of output consisting of 100 array elements in a grid with a width of 10 elements per line.
Actual result is a mess of new line loops and further headache to me.
Pretty common issue just use a modulus based on the index i:
for (int i = 0;i < 100;i++) {
printf("%d , ", test[i]);
if ((i + 1) % 10 == 0) {
printf("\n");
}
}
If you want nicely formatted output however you'll need:
#include <iomanip>
and
std::cout << std::setw(/*max_len*/) << test[i];
The simplest solution would be to print the delimiter (i%10 == 0) ? "\n" : ", ". You correctly recognized that taking the remainder on every iteration of the loop is inefficient, and wanted to write one that would print ten elements followed by a newline.
The trick there is to write an inner loop that increments a second counter, j, do all your output within the inner loop, and then update i at the bottom of the outer loop. A simplified example:
#include <array>
#include <iostream>
#include <stdlib.h>
#include <time.h>
using std::cout;
int main()
{
constexpr size_t ARRAY_LEN = 100;
std::array<int, ARRAY_LEN> test;
{
// Quick and dirty initialization of the random seed to the lowest 30
// or so bits of the system clock, which probably does not really have
// nanosecond precision. It’ll do for this purpose.
timespec current_time;
timespec_get( &current_time, TIME_UTC );
srand(current_time.tv_nsec);
}
for (int i = 0; i < test.size(); i++){
//Set array to rand
test[i] = rand() % 44 + 55;
}
for ( int i = 0, j = 0;
i < test.size();
i += j ) {
for ( j = 0; j < 10 && i + j < test.size(); ++j ) {
cout << test[i + j] << ' ';
}
cout << '\n';
}
return EXIT_SUCCESS;
}
Note that the version you wrote does not initialize the standard library’s random seed, so you get the same (poorly-distributed) random numbers. You could write a version that uses the much superior STL random-number generators and perhaps <chrono>, instead of the C versions, but that’s a bit outside the scope of your question.

How to search and sort a 2D array

We are doing a program in class to read in about 100 lines of code, store it, and sort it. The code is first an employee's ID number followed by their sales. There are only 12 employees. We have to store it in a 12x4 2D array. We have to have the employee number, the total number of sales they made (counter), their total sales amount, and the average of all their sales/count.
My issue is figuring out how to write a search function that is not already in the library. He mentioned returning the subscript from the search function to associate that ID number with a subscript. We can only use user-created functions and 2d arrays. Have not learned pointers or vectors yet.
So far I have done the bare bones b/c I'm not sure how to continue reading 100 values, but condensing them down to 12 people. Could someone please help demonstrate how to begin sorting this 2D array? Please be as verbose as possible as this is only my 2nd semester. I apologies if I have not explained it properly.
// example of data in file. ID number on left and a sale made on right.
-322 10.80
-848 920.00
-828 1267.00
-848 8320.00
-229 66330.00
// the bubble sort we have to use
void sort(float sales[], int size)
{
int i, j;
for(i = 0; i < size - 1; i++) {
for(j = 0; j < size - i - 1; j++) {
//checking if previous value is
//grater than next one or not
if(sales[j] > sales[j+1]) {
float temp = sales[j];
sales[j] = sales[j+1];
sales[j+1] = temp;
}
}
}
}
// completely stuck here
int search_ID(float sales[][4])
{
int r;
for(c = 0; c <= 0; c++) {
for(r = 0; r < 13; r++) {
if(sales[r][c] != sales[r][c]) {
//was thinking of if the ID number
//matches or doesn't match perform a t/F
}
}
}
return sub;
}
// the avg sales for each employee
float avgSale(float sales[][4], int rowNum)
{
int r, c, totalSales;
float avg;
// would just use a for loop in main to call each row num.
for(r = rowNum; r <= rowNum; r++) {
for (c = 3; c < 4; c++) {
avg=sales[r][c]/totalSales;
}
}
return avg;
}
// we have to print a report with ID, Num sales, total sales, and avg for
// each so the 4 columns
void printReport(float sales[][4])
{
int r, c;
cout << fixed << setprecision(2);
for(r = 0; r < 13; r++) {
for(c = 0; c <= 1; c++) {
cout << sales[r][c] << " ";
}
cout << endl;
}
}
int main()
{
infile.open("C://data//input//Sales.txt");
outfile.open("C:\\data\\SalesmenReport.txt");
//check if file opens
if(!infile) {
cout << "File did not open. Please try again."<<endl;
return 0;
}
int size=12;
int sub;
float avg;
float sales[size][4];
int r, c, sub;
for(r = 0; r < 13; r++) {
for(c=0;c<=1;c++) {
infile >> sales[r][c];
// he showed us this as an example to call the search, idk where
// to put it or what to put in it.
sub = search_ID(sales);
}
}
printReport(sales);
avg = avgSale(sales, 0);
Edit & Run
I expect when the program is completed to be able to print the 12 employee ID numbers, their number of sales, total amount each salesman made, and each person's average clear across left to right in a table.
You need to pass empId (to be searched) as a parameter to the function. For example, following function will return 1 if it finds the record with given employee id, otherwise 0.
int search_ID(float sales[][4], int empIdToBeSearched)
{
int r, found;
found = 0;
for(r = 0; r < 13; r++) {
if(sales[r][0] == empIdToBeSearched) {
found = 1;
break;
}
}
return found;
}
And while sorting the records you should apply the sorting algorithm on any column that you want but while swapping the data you should swap the entire row and not just the particular cell. So in this case your temp (used in sort function) should be 2-D array something like float temp[1][4].

Having a logical issue with recursion-based N-nested for loops

I've searched and found similar problems, but they all didn't seem to fit with mine. Basically, I need to write a recursive function that nests a loop N times and prints everything only on the very last loop. If you can find another solution to the problem, that would be great.
0 = *
1 = +
2 = ABC
3 = DEF
...
8 = STU
9 = VWXYZ
Here is the full code: http://pastebin.com/2YdQ693N
Here is a hard-coded N=3 example:
//sout is a vector<string>
for(int i = 0; i < sout[0].size(); i++)
{
for(int j = 0; j < sout[1].size(); j++)
{
for(int k = 0; k < sout[2].size(); k++)
{
cout << sout[0][i] << sout[1][j] << sout[2][k] << endl;
}
}
}
the following output of this particular example (input is "123"):
+AD
+AE
+AF
+BD
+BE
+BF
+CD
+CE
+CF
The closest I got before coming here was a recursion function similar to this one here: http://v2.cplusplus.com/forum/beginner/68434/ but I couldn't get it to work for my case.
I need the indexes to go in this type of order:
000
001
002
010
011
012
020
021
022
except the length has to be variable (and therefore height as well).
Here is my recursion function I've been trying so far:
void recurseLoop(const vector<string>& sout, int numLoops)
{
if(numLoops > 0)
{
for(int i = 0; i < sout[1].size(); i++)
{
//cout << i;
recurseLoop(sout, numLoops - 1);
}
}
else
{
//cout << endl;
return;
}
}
However the result that 'i' gives is pretty much unintelligible and I'm having trouble getting the correct structure of loops/if statements to get this to work. Any help is appreciated!
void recursion(int N, const vector<string>&sout, vector<int>&index, int I=0)
{
if(I<N-1)
for(index[I]=0; index[I]<sout[I].size(); index[I]++)
recursion(N,sout,index,I+1);
else if(I==N-1)
for(index[I]=0; index[I]<sout[I].size(); index[I]++) {
for(int k=0; k<N; ++k)
std::cout << sout[k][index[k]];
std::cout << std::endl;
}
}
void loop_N_times(const vector<string>&sout)
{
std::vector<int> index(sout.size());
recursion(sout.size(),sout,index,0);
}
Why are you always use sout[1] in recursion? It probably should be something like
for (int i = 0; i < sout[sout.size() - numLoops].size(); ++i)

c++ simple function to add numbers

first of all, I just want to say I'm newbie in c++, and I'm tring to solve a problem that I have, but no luck so far. The code is:
const int MAX = 100;
void funkcija(int niz[], int n, int& poc, int& sko)
{
for(int i = 0; i < n; i++)
{
niz[i] = poc + sko;
}
}
int main()
{
int niz[MAX];
int start, jump;
cout <<"Start element: ";
cin >> start;
cout <<"Jump element: ";
cin >> jump;
funkcija(niz, MAX, start, jump);
cout << "Ispis pocevsi od " << start << " sa skokom od " << jump << " jest: " << niz[1]<< endl;
getchar();
return 0;
}
What the program is supposed to do is: It asks me for start number. Lets say I pick 15. Then it asks for jump number. I select 11. The print should go "15, 26, 37, 48, 59, 70, 81, 92." (15+11 = 26, 26+11 = 37...) and it should print all numbers until 100, which is my MAX. If I change the MAX to 1000 it should print all numbers until 1000.
You always set the same value in your table elements : poc + sko.
You want to put poc in niz[0] then
for(int i = 1; i < n; i++) {
nit[i] = niz[i-1] + sko;
}
for(int i = 0; i < n; i++)
{
niz[i] = poc + sko;
}
You say you want "15+11 = 26, 26+11 = 37...".
Can you think of why this isn't doing that?
For output, you only are outputting a single element from your array (the second element):
<< niz[1]
The problem lies in the for loop. Loop isn't updating the next number in the sequence.
for(int i = 0; i < n; i++)
{
niz[i] = poc ;
poc += sko; // This should be added.
}
Also, the condition is wrong. It should be poc < n. Why do you need to pass n, when you have MAX as the global variable.
If I understood correctly that you want 100 numbers, the code should look like this:
void funkcija(int niz[], int n, int poc, int sko)
{
for(int i = 0; i < n; i++)
{
niz[i] = poc;
poc = poc + sko;
}
}
Note that I removed the ampersands (&) from your parameters. Adding these makes them reference parameters, which means after the function returns, the values of start and jump in your main() function are also changed.
Has it occurred to anybody that the third expression in the for loop does not necessarily have to be i++? That particular expression increments i by 1. If you wanted to increment it by some other quantity (e.g., the "jump elemement"), what expression could you use?