learning c++ need help with a barchart

Basically I have to do the exercise is as follows - A function DisplayListAsBarChart that may be passed an array of values. The function
should then display the array of values as a bar-chart.

This is what I have so far but when I compile it, bars start showing up like
this

1 |
4 | || ||
7 || || |||

can someone outline what I'm doing wrong and the solution would be appreciated too.

void DisplayListAsBarChart ( int list[] )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

#include "stdafx.h"
#include <iostream>
using namespace std;

void  DisplayListAsBarChart(int list[]);

int main()
{
   
	
	int list[12];
	for (int i = 0; i < 12; i++)
	{

		cin >> list[i];
		DisplayListAsBarChart(list);

	}
	
	
	
	return 0;
}

void  DisplayListAsBarChart(int list[])
{

	char barChart[10][12];

	for (int row = 0; row < 10; row++)
	{

		for (int col = 0; col < 12; col++)
		{

			barChart[row][col]= ' ';

		}
	}

	for (int col = 0; col < 12; col++)

	{

		for (int row = 9; row > 9 - list[col]; row--)
		{

			barChart[row][col] = '|';

		}


	}


	{

		for (int row = 0; row < 10; row++)
		{


			for (int col = 0; col < 12; col++)
			{
				cout << barChart[row][col] << " ";

			}

		}


		cout << endl;

	}

	
}
Strange that you got output, when I compiled and runned this it crashes because DisplayListAsBarChart is called with an uninitialized array.

So I would start with moving the call to DisplayListAsBarChart out of the for loop, so the array is properly initialized.

Then I would remove the "using namespace std;" because the variable list that you use is a reserved word in the namespace std. In general I would recommend to not use "using namespace std;" until you are familiar with every function and keyword in the standard library (which equals never).

Subsequently I would think that you should think about what a row is and what a column is in your graph. Specifically: when you start to use std::cout each row in your graph table is a single line in the console.

And finally: don't include stuff you don't use. http://www.cplusplus.com/articles/1TUq5Di1/

Kind regards, Nico

Last edited on
Topic archived. No new replies allowed.