Please help me understand the code.

Hello.
This is a code for array o size 20 where you can put numbers and they will be in ascending order. however, I do not understand why in last for why do we cout new integer i and not the integers that we have already declared in last for. Why cant we use last for and not the above one?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  #include <iostream>
using namespace std;

int main() {
	int a[20], shecvla; // declaring
	for ( int i = 0; i < 20; ++i ) // 20 ricxvi
		cin >> a[i]; // vsvavt 20 ricxvs i-shi
	for ( int i = 0; i < 20; ++i ) {
		for ( int j = i; j < 20; ++j ){
			if( a[j] < a[i] ){ // j=i-s da tu j-i naklebia i-ze mashin i-i ucvlis adgils j-s adgils da win dgeba
				shecvla = a[i];
				a[i] = a[j];
				a[j] = shecvla;
            
			}
		}
	}
    
	for ( int shecvla = 0; shecvla < 20; ++shecvla )
		cout << a[shecvla] << " "; // gamogvyavs
	return 0;



}
As they are now, lines 8-17 are trivial to split off into another function with a single distinct purpose. Mixing in output would muck things up a bit.

However, yes, if you wanted, you could have the output done in the outermost loop of your sorting code.

-Albatross
Topic archived. No new replies allowed.