134k views
5 votes
Write a program to display a histogram based on a number entered by the user. A histogram is a graphical representation of a number (in our case, using the asterisk character). On the same line after displaying the histogram, display the number. The entire program will repeat until the user enters zero or a negative number. Before the program ends, display "Bye...".The program will ask the user to enter a non-zero positive number. Using a while loop, validate that the number is not greater than 40, and if so, re-ask for the number. Put the entire program into a sentinel-controlled loop so that the user can enter either zero (0) or a negative number to end the program.Create constants for 1 (the minimum number for the histogram), and 40 (the maximum number for the histogram), and use these constants in the prompts, the validation condition and error message, and the sentinel-controlled loop and the histogram loop.

User Mansfield
by
3.4k points

1 Answer

1 vote

Answer:

// CPP program to make histogram of an array

#include <bits/stdc++.h>

using namespace std;

void printHistogram(int arr[], int n)

{

int maxEle = *max_element(arr, arr + n);

for (int i = maxEle; i >= 0; i--) {

cout.width(2);

cout << right << i << " | ";

for (int j = 0; j < n; j++) {

// if array of element is greater

// then array it print x

if (arr[j] >= i)

cout << " x ";

// else print blank spaces

else

cout << " ";

}

cout << "\\";

}

// print last line denoted by ----

for (int i = 0; i < n + 3; i++)

cout << "---";

cout << "\\";

cout << " ";

for (int i = 0; i < n; i++) {

cout.width(2); // width for a number

cout << right << arr[i] << " ";

}

}

// Driver code

int main()

{

int arr[10] = { 10, 9, 12, 4, 5, 2,

8, 5, 3, 1 };

int n = sizeof(arr) / sizeof(arr[0]);

printHistogram(arr, n);

return 0;

}

Step-by-step explanation:

The idea is to print the given histogram row by row. For every element, we check if it is greater than or equal to current row. If yes, put a ‘x’ for that element. Else we put a space.

User Randomize
by
3.5k points