Reverse array in C++

j+e's Avatar, Join Date: Feb 2009
j+e
Light Poster
Hi! I have just started programming, and I have a question for my assignment:

When the input is ABCDE, i want the output to be EDCBA. But for some reason I cant understand he output i get is: EDCDE

My code is:
"
for (int i = 0; i < b; i=i++)
{
char temp1 = a[i];
a[i] = a[(b-1)-i];
a[(b-1)-i] = temp1;
cout << a[i] ;
"

b is the word...

Please help me Thank you!
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Just loop it reverse and thats it.
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
> i=i++

Um, no. Either use i++ on its own or use i=i+1.

Try as a test displaying the values of i and (b-1)-i in the loop instead. What values do you expect? What values do you get? Does that explain why you get EDCDE?
cpulocksmith's Avatar, Join Date: Jul 2008
Skilled contributor
how does this grab ya?
Code:
#include <iostream>
using namespace std;

int main(){
char word[5]={'b','i','r','d','s'};
char temp1[5];

for (int i = 5; i > -1; i--)
{
char temp1 = word[i];
word[i] = temp1;
cout<<word[i];
}
cout<<endl;
}
hope it helps. i think this is what xpi0t0s was saying. you just turn the signs in the for loop, and make everything opposite.
also i the for loop you put i=i++, i++ will work fine ^^

Last edited by cpulocksmith; 19Feb2009 at 05:13.. Reason: word[i] = word[i]; what the hell?
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Did you run that code cpulocksmith?
What did word contain after it finished?
What's the point of word[i] = word[i]; ?
cpulocksmith's Avatar, Join Date: Jul 2008
Skilled contributor
ha ha ha... woops...lol...
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
This would do nothing.

char temp1 = word[i];
word[i] = temp1;
Ryzer's Avatar, Join Date: Feb 2009
Go4Expert Member
Code:
int size = 5;
char value1[size] = {'a','b','c','d','e'};
char value2[size];

for(int i = 0; i < size; i++) {
  value2[i] = value1[i];
}
for(int j = size - 1; j > -1; j--) {
  cout << value[j];
}
don't have my compiler on this cpu so didnt test it but unless i'm missing something it should work correct me if i'm wrong
j+e's Avatar, Join Date: Feb 2009
j+e
Light Poster
Thank you very much Ryser! It worked
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
You dont need value2 array as you are just printing the array from last.