Archived

This topic is now archived and is closed to further replies.

Reversing array index values for output?

This topic is 5651 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Greetings all, I''m in the midst of learning C++ and have come across a trivial problem for most experienced programers...except me. I''m trying to reverse the orders of the values stored in the array indices. The values at these indices are unknown until runtime (hence using variables in place of the input). I want it to loop backwards. I have other functions set up (not shown here) that set up a loop to count down so here''s the code so far: // In: x The value for which I may use for whatever (I don''t // why I have it here.) I''m thinking third // argument would be useful here? // // xnum The array name // arr The array size // void Reverse_array(double x, double xnum, double arr) { for(int i = 0; i < ? ; i++) { (i - 1) } } Aaaand....well that is it. Anyone?

Share this post


Link to post
Share on other sites
Well, assuming a zero based array...

A is the array (zero based)
I is an index variable
Swap(index1,index2) is a function that swaps 2 entries in the array using a temporary varible
Length(array) is a function that returns the number of elements in an array.


FOR I = 0 to (Length(A) div 2)-1
Swap(I,Length(A)-1-I)
NEXT I


I pretty sure that will work.

2nd question:
[source]your code[/source]

Share this post


Link to post
Share on other sites
quote:
Original post by Gamersez
I'm trying to reverse the orders of the values stored in the array indices.

What? Do you mean you are trying to reverse an array or to iterate in reverse order through an array? Here's an example of both, but using vectors (which you should prefer over arrays):


      
#include <vector>

#include <iostream>

#include <algorithm>

int main()
{
std::vector<int> v;
for(int i=0; i<10; ++i)
{
v.push_back(i);
}

std::vector<int>::iterator it;
std::vector<int>::iterator end = v.end();

for(it = v.begin();it != end; ++it)
{
std::cout << (*it) << "\n";
}

// reverse the sequence:

std::reverse(v.begin(), v.end());

for(it = v.begin();it != end; ++it)
{
std::cout << (*it) << "\n";
}

// print the sequence in reverse:

std::vector<int>::reverse_iterator rit;
std::vector<int>::reverse_iterator rend = v.rend();

for(rit = v.rbegin(); rit != rend; ++rit)
{
std::cout << (*rit) << "\n";
}
}


Note that the Standard Library algorithms will work with arrays aswell, using pointers as iterators.

quote:
One other thing...how do I get that neato scroll bar with white spacing for which I may display the code? Is it HTLM coded?


See the FAQ.

[edited by - SabreMan on June 26, 2002 11:35:55 AM]

Share this post


Link to post
Share on other sites