I was trying to print out some kind of graph of an array’s integers making some "bars" of the same length so that i could later print them vertically and not horizontally. At first my code printed the graph upside down so i "inverted" the for cycle. I run the function twice and it now only works the first time or doesn’t work at all or it prints the array partially the second time (everytime i run the code the elements in the arrays vary). Any ideas? I’m genuinely desperate.
before
void printArrInt(int arr[], int len) {
int max = findMaxValue(arr, len);
std::string bars[len];
for (int i = 0; i < len; i++) {
for (int j = 0; j < arr[i]; j++) {
bars[i].append("@");
}
for (int j = 0; j < (max - arr[i]); j++) {
bars[i].append(" ");
}
}
for (int i = 0; i < max; i++) {
for (int j = 0; j < len; j++) {
std::cout << bars[j][i];
}
std::cout << std::endl;
}
std::cout << std::endl << std::endl;
}
after
void printArrInt(int arr[], int len) {
int max = findMaxValue(arr, len);
std::string bars[len];
for (int i = 0; i < len; i++) {
for (int j = 0; j < arr[i]; j++) {
bars[i].append("@");
}
for (int j = 0; j < (max - arr[i]); j++) {
bars[i].append(" ");
}
}
for (int i = max; i > 0; i--) {
for (int j = 0; j < len; j++) {
std::cout << bars[j][i];
}
std::cout << std::endl;
}
std::cout << std::endl << std::endl;
}
>Solution :
In your first implementation, it stops just before i reaches the value max (i<max). In your second, it starts at max instead of max-1 as it should. So you may be getting an out-of-bounds error. Also in your second implementation, it will not run with i==0 but will stop at i==1 because i>0 will be evaluated after i-- and when i is 1, i-- is zero and fails the test.