Starting to do arrays and my first question is...

Wrtie a loop to print the elements of an array of int called numbers.
You only know that the array has 5 elements.
i


My 1st attempt is going like this....

#include <iostream>
using namespace std;

int main()
{
int number[5];

int i = 0;

while ( i < 5) 
{
number [i] = i + 1;

i++;
cout << number;
}
return 0;
}

Am I even going in the right direction? I'm just following my text text book.

Not quite. Assume you have this :

int numbers[5] = {1,2,3,4,5};

and now you want to print all values in the array.

Here are some hints. Generally you would want to use a for-loop when you know how many elements you want to iterate over. Google for loops.

To access an element in the array you can use the subscript operators like so

numbers[0]; //the first element
numbers[1]; //the second element
//...and so on

now all you need to do is combine what I said above into one. Give it another try.

For what you are doing, it might be best to use a for loop. Such as:

#include <iostream>
using namespace std;
 
int main()
{
int number[5];
 

 
for (int i = 0; i<5; i++)
{
number [i] = i + 1;
cout << number << endl;
}

system("PAUSE");
return 0;
}

This makes the code simpler and easier to work with. Now, all i did here was adjust your code into a for loop, it will still have the same output, because you are forgetting one important part when accessing your array to draw values from it. If you look at where you are assigning values into your array, and where you are trying to pull them out, you will see the difference.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.