0
Why is output 323? Not 321
6 Réponses
+ 3
First loop: // c is "123"
c[0] = c[2];
c is "323".
Second loop: // c is "323"
c[1] = c[1];
c is "323".
Third loop: // c is "323"
c[2] = c[0];
c is "323"
Ends
You can get "321 if you copy the original string to another variable.
+ 2
Try to print string <c> inside the loop after you do character swap. You'll see why that is happening 👍
+ 1
Because you have overwritten c[0]
+ 1
This works...
#include <iostream>
using namespace std;
int main() {
string c= "123";
int a = c.length()-1;
string b=c;
for (int i=0; i<=a; i++) {
c[i]= b[a-i];
}
cout<<c;
return 0;
}
+ 1
Quantum, It turns out that the larger array overlaps the smaller one ( c[0]=c[2] out c[2] and c[2]=c[0] out c[2])?
+ 1
Exactly, because you have overwritten the original value you are trying to assign.