Arrays

This is the first part of my assignment I think I have the first and third part for some reason I am not understanding the part decrementing the loop counter. Any guidance in this area would be greatly appreciated.



//First, write a simple program that will read 5 numbers from the Console (user input). Store these values into an array of int []. Using the length of the array in a for() loop and decrementing the loop counter, write the array values in reverse order to the screen.


#include <iostream>

using namespace std;

int main()

{
int array[5];
int counter;
int i = 0;



cout << "Please enter five numbers: ";


for (counter = 0; counter < 5; counter++)
{
cin >> array[counter];

}

cout << endl;


//decrementing the loop counter having trouble here!!!!!

cout << "Counting down the numbers: ";

for(i = 0; i < 5; i = i++)
cout << i << " ";

cout << endl;



cout << "The numbers in reverse order are: ";

for (counter = 4; counter >= 0; counter--)
cout << array[counter] << " ";

cout << endl;




return 0;

}


Please use the 'Insert Code' button when adding code to a posting - it makes it much easier to read. Then put the code between the '[Code ]' and '[ /Code]' tags for nice formatting. It also gives line numbers which can make answering the question simpler!

As far as I can tell yuo have actually done all you need - and a bit extra!
Just remove the section
1
2
3
4
5
6
7
8
//decrementing the loop counter having trouble here!!!!!

cout << "Counting down the numbers: ";

for(i = 0; i < 5; i = i++)
    cout << i << " ";

cout << endl;

(see, it looks much nicer formatted!)

You are actually doing the decrementing a loop counter in the next loop
1
2
for (counter = 4; counter >= 0; counter--) //counter is the loop counter
   cout << array[counter] << " ";          //counter-- is decrementing it:-) 

The only change I woudl make would be to declare a constant for the size of the array
 
const int ARRAY_SIZE = 5;

and use that in place of the hard coded '5''s in the code
1
2
3
4
5
int array[ARRAY_SIZE];
...
for (counter = 0; counter < ARRAY_SIZE; counter++)
...
etc.

as this makes it very clear where the number comes from, and as good practice for later when you have a (larger) program with arrays and realise you need to change the array size if all references are to a constant then all you need to do is change the value of that constant - quicker and much less likely to introduce a bug when you miss one!
Last edited on
Thank you so much for all your help with this program. I surprised myself that I knew how to do something :0).
Topic archived. No new replies allowed.