write a program that read in an array of integers-- ideally from a text file. and then displays a histogram of those numbers, divided into the ranges 0-9, 10-19 ,20-29, and so forth, up to the range of containing only the valye 100.
Please help me to write a efficient and better code..
#include <iostream>
#include <iomanip>
#include "genlib.h"
#include "strutils.h"
#include <fstream>
void Histogram(int*); //Function prototype
void print(string*);
int main(){
int arr[10] = {2,4,5,23,26,29,6,100,100,80}; //integer array inialization
ofstream out("arr.txt"); //open file for write
for (int i =0;i<10;i++){
out << arr[i] << ' '; // store data in file
}
for(int i=0;i<10;i++){
arr[i]=0; //initialization array with zero, so can get values from file
}
out.close(); //close is must.
ifstream in("arr.txt"); //open file for read
for(int i=0;;i++){
in >> arr[i]; // reading data from file into memory
if(in.fail()) break;
}
Histogram(arr); //call Histogram Function
return 0;
}
void Histogram(int *arr){
string str[11]; // for storing number of "*"
for(int i =0;i<10;i++){
if(arr[i]>=0 && arr[i] <10){
str[0]+="*";
}else
if(arr[i]>=10 && arr[i] <20){
str[1]+="*";
}else
if(arr[i]>=20 && arr[i] <30){
str[2]+="*";
}else
if(arr[i]>=30 && arr[i] <40){
str[3]+="*";
}else
if(arr[i]>=40 && arr[i] <50){
str[4]+="*";
}else
if(arr[i]>=50 && arr[i] <60){
str[5]+="*";
}else
if(arr[i]>=60 && arr[i] <70){
str[6]+="*";
}else
if(arr[i]>=70 && arr[i] <80){
str[7]+="*";
}else
if(arr[i]>=80 && arr[i] <90){
str[8]+="*";
}else
if(arr[i]>=90 && arr[i] <100){
str[9]+="*";
}else
if(arr[i]==100){
str[10]+="*";
}
}
print(str); // call print function for display formated data
}
void print(string *str){
int i,j =0; // Display data
for (i=0;i<=100,j<11;i+=10,j++){
cout << setw(8)<< IntegerToString(i) + " :" << str[j] << endl;
}
}
Output remain the same as in the image file...