Why is output 323? Not 321 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
27th Mar 2021, 7:54 AM
Тимур Завьялов
Тимур Завьялов - avatar
6 Answers
+ 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.
27th Mar 2021, 8:31 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 2
Try to print string <c> inside the loop after you do character swap. You'll see why that is happening 👍
27th Mar 2021, 8:30 AM
Ipang
+ 1
Because you have overwritten c[0]
27th Mar 2021, 8:50 AM
Jan
Jan - avatar
+ 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; }
27th Mar 2021, 9:24 AM
Jan
Jan - avatar
+ 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])?
27th Mar 2021, 9:56 AM
Тимур Завьялов
Тимур Завьялов - avatar
+ 1
Exactly, because you have overwritten the original value you are trying to assign.
27th Mar 2021, 10:00 AM
Jan
Jan - avatar