C++ Nested Loops and Histogram

Hello, I am making a histogram program that prints on the ith line the ith char in the symb array the number of times that appear in the ith index of count. Ex. line 0: a, line 1: bbbbb, etc

But When I run my program in the complier, it seems to print the wrong way.
What can I do solve this?

#include <iostream>
using namespace std;

const int countSize = 10;

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
	int count[] = {1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
	char symb[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'k'};

	for (int i = 0; i < countSize; i++)
	{
		for (int j = 0; j < count[i]; j++)
			cout << symb[j] << endl;
	}

	return 0;
}

First of all, there's a problem with your code.
You have declared and initialized const int countSize = 10, but you don't use it to set the size of the arrays. Your count[] array has 11 elements in it, and your symb[] array only has 9.

In addition, you should remove the std::endl from the inner-most for loop, and place it after the inner-most for loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int main(int argc, char* argv[]) {

	const unsigned short nElements = 4;

	unsigned short values[nElements] = {1, 2, 3, 4};
	char characters[nElements] = {'a', 'b', 'c', 'd'};

	for(unsigned short i=0; i<nElements; ++i) {
		for(unsigned short j=0; j<values[i]; ++j) {
			std::cout << characters[i];
		}
		std::cout << "\n";
	}

	std::cin.get();
	return 0;
}
Last edited on
Topic archived. No new replies allowed.