Having trouble with histogram c++ function. It is passed an array of values then
ID: 3930439 • Letter: H
Question
Having trouble with histogram c++ function. It is passed an array of values then I run it through my algorithm and then the function is supposed to return an array. I believe the program is not liking my algorithm but I do not know why. This is what I have so far
int* histogram(int* a)
{
static int histArray[100] = { 0 };
for (int i = 0; i < 100; i++)
histArray[a[i]]++;
return histArray;
}
Example of passed array: {1,2,2,1,3,4,5,6,7}
should return an array such: {0,2,2,1,1,1,1,1,0,0,} for a histogram with 10 slots.
Explanation / Answer
#include <iostream>
#include <cstdlib>
using namespace std;
int* histogram(int *a,int len)
{
int *histArray = new int[10];
for (int i = 0; i < 10; i++)
{
histArray[i]=0;
}
//int len = sizeof(a)/sizeof(int);
//cout<<len<<"**"<<endl;
for (int i = 0; i < len; i++)
{
histArray[a[i]]++;
}
/*for (int i = 0; i < 10; i++)
{
cout<<histArray[i]<<' ';
}*/
return histArray;
}
int main()
{
int b[] = {1,2,2,1,3,4,5,6,7};
int *a= new int[9];
for(int i=0;i<9;i++)
{
a[i]=b[i];
}
//int len1 = sizeof(a)/sizeof(int);
//cout<<len1<<endl;
int *hist = histogram(a,9);
//int len = sizeof(hist)/sizeof(int);
//cout<<len<<'('<<endl;
for (int i = 0; i < 10; i++)
{
cout<<hist[i]<<' ';
}
cout<<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.