C++/C++help
Expert: Zlatko - 11/7/2010
QuestionI am trying to build a 2 dimensional array of random numbers, which I
accomplished. I am also trying to find out the average of the randomized
numbers. Here is my code. Maybe you can help me figure out why my average
keeps equaling 2, no matter how many times i randomize the array. Thank
you!
int main(void)
{
const int COL=7,ROW=7;
int
square[COL][ROW]={(rand()%100),(rand()%100),(rand()%100),(rand()%100),(rand
()%100),(rand()%100),(rand()%100),(rand()%100),(rand()%100),(rand()%100),(ran
d()%100),(rand()%100),(rand()%100),(rand()%100),(rand()%100),(rand()%100),(ra
nd()%100),(rand()%100),(rand()%100),(rand()%100),(rand()%100),(rand()%100),(r
and()%100),(rand()%100),(rand()%100),(rand()%100),(rand()%100),(rand()%100),(
rand()%100),(rand()%100),(rand()%100),(rand()%100),(rand()%100),(rand()%100),
(rand()%100),(rand()%100),(rand()%100),(rand()%100),(rand()%100),(rand()%100)
,(rand()%100),(rand()%100),(rand()%100),(rand()%100),(rand()%100),(rand()%100
),(rand()%100),(rand()%100),(rand()%100),},a,b,cont;
cout<<"The array is:"<<"\n"<<endl;
for (a=0;a<COL;++a)
{
cout<<endl;
for (b=0;b<ROW;++b)
cout<<setw(4)<<square[a][b];
cout<<"\n";
}
int sum = 0;
int average =0;
sum+=[COL];
average = sum/49;
cout<<"The average of the array is:"<<average<<endl;
return 0;
}
AnswerHello Jeniffer
I don't know how you got any output from your program, because the version you sent me doesn't compile.
Here is what you need to do.
Add
#include <stdlib.h>
#include <iostream>
#include <iomanip>
using namespace std;
to the top of your program.
Look at how sum is being calculated. It is not in any loop so it cannot sum up the contents of square. The syntax of sum+=[COL] is not valid C. You need to specify the array name, and 2 indexes. Look at how an array element is accessed in the cout line
cout<<setw(4)<<square[a][b];
You need to access the array element in the same way when calculating the sum.
Don't forget to set your sum to 0 before the start of the calculation.
Ok, the next part is optional
-----------------------------------------------------------
Once you get your program fixed and running, you will notice that the output is the same in every run. That is because random numbers aren't really random. To get different results at each run, you need to seed the random number generator with a different value on each run. Put
srand(time(NULL));
at the top of your main function to seed the random number generator.
Your square can be initialized in a nicer way. You can use a loop like this:
int square[COL][ROW];
int a, b;
for (a = 0; a < COL; ++a)
{
for(b = 0; b < ROW; ++b)
{
square[a][b] = rand()%100;
}
}
It is much less awkward and much less error prone than having the long list of initializers.
Keep trying, you're almost done. If you need more help, let me know.
Best regards
Zlatko