Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Reverse array in C++ (http://www.go4expert.com/forums/reverse-array-cpp-t16253/)

j+e 18Feb2009 17:04

Reverse array in C++
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 18Feb2009 18:49

Re: Reverse array in C++
Just loop it reverse and thats it.

xpi0t0s 18Feb2009 21:09

Re: Reverse array in C++
> 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 19Feb2009 04:04

Re: Reverse array in C++
how does this grab ya?

#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;

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 ^^

xpi0t0s 19Feb2009 04:35

Re: Reverse array in C++
Did you run that code cpulocksmith?
What did word contain after it finished?
What's the point of word[i] = word[i]; ?

cpulocksmith 19Feb2009 05:13

Re: Reverse array in C++
ha ha ha... woops...lol...

shabbir 19Feb2009 09:08

Re: Reverse array in C++
This would do nothing.

char temp1 = word[i];
word[i] = temp1;

Ryzer 19Feb2009 10:04

Re: Reverse array in C++

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 :confused: correct me if i'm wrong

j+e 19Feb2009 12:17

Re: Reverse array in C++
Thank you very much Ryser! It worked :)

shabbir 19Feb2009 13:02

Re: Reverse array in C++
You dont need value2 array as you are just printing the array from last.

All times are GMT +5.5. The time now is 03:49.