Reputation: 89
Can you help me with a problem on populating an array of 5 circles with random numbers. The random number would be the radius of the circles. Here is my code:
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
// Array 2, below section is to populate the array with random radius
float CircleArrayTwo [5]; // store the numbers
const int NUM = 5; // Display 5 random numbers
srand(time(NULL)); // seed the generator
for(int i = 0; i < NUM; ++i)
{
CircleArrayTwo[i] = rand()%10;
}
cout << "Below is the radius each of the five circles in the second array. " << endl;
cout << CircleArrayTwo << endl;
system("PAUSE");
return 0;
}
Currently is output the following:
Below is the radius each of the five circles in the second array. 002CF878
Where am I going wrong?
Any help is much appreciated
Upvotes: 1
Views: 2410
Reputation: 156
CircleArrayTwo
is a pointer. When you print a pointer, it prints a memory address, like the one you provided. In order to print the values of an array, you need to use the []
notation that you have for the insert.
You could loop over the values in the array and print each one:
for (int i = 0; i < NUM; ++i) { cout << CircleArrayTwo[i] << endl; }
Upvotes: -1
Reputation: 2342
In C(and C++) arrays are almost equivalent to pointers to the beginning of memory location. So you're just outputting the adress of the first element; To output all elements introduce another loop:
for(int i = 0; i < NUM; ++i)
{
cout << CircleArrayTwo[i] << endl;
}
Upvotes: 0
Reputation: 3269
The way you populated the array is correct, however you cannot print an array like that. You need to write a loop to output the values one by one.
Upvotes: 1
Reputation: 227370
You are printing the address of the first element of the array. You could loop over the array and print each element:
for(int i = 0; i < NUM; ++i)
{
std::cout << CircleArrayTwo[i] << ", ";
}
std::cout << "\n";
Or, if you have C++11 support,
for (auto& x : CircleArrayTwo) {
std::cout << x << ", ";
}
std::cout << "\n";
Upvotes: 5