0

Wahts is the problem of my code and why it doesnt sort truly?

#include <iostream> using namespace std; int main() { int ages[5]; int temp; for (int i = 0; i < 5; i++) { cin >> ages[i]; } for(int i=0;i<5;i++) {for(int j=i+1;j<6;j++) {if(ages[i]<ages[j]) temp=ages[i]; ages[i]=ages[j]; ages[j]=temp; }} for(int i=0;i<5;i++) cout<<ages[i]; return 0; }

4th Oct 2021, 8:34 AM
Nariman Tajari
Nariman Tajari - avatar
3 Answers
+ 4
You have 3 lines of statement for swapping the array elements (on a condition) inside the `if` block. For this reason, you need tp wrap the `if` block in curly brackets for( ... ) { for( ... ) { if( ... ) { // swap the elements here ... } } }
4th Oct 2021, 8:59 AM
Ipang
+ 2
Yes there will not be any error, but the sort isn't working because the 3 statement for swapping the elements' values isn't working correctly. Conditionals and loops only execute one immediate line (the body) when no curly brackets are enclosing the body. Your `if` block code is processed as follows if( ages[ i ] < ages[ j ] ) temp = ages[ i ]; The following 2 lines are processed disregarding whether the `if` conditional evaluates to true or false. ages[ i ] = ages[ j ]; ages[ j ] = temp;
4th Oct 2021, 9:46 AM
Ipang
+ 1
Ipang but my code has run without any error my problem is why the output is not the sorted array that i gave it unsorted as input?
4th Oct 2021, 9:34 AM
Nariman Tajari
Nariman Tajari - avatar