well lets say that this program will input only 3 numbers by changing the arraySize from 20 to 3
int array[3];
// means that we declare an array ,that can holds three number
1 2 3
|
cout << "Enter 20 number " << endl;
for(int i=0;i<arraySize;i++)
cin >> array[i];
| |
here we ask the using to enter those three numbers for example the user enters 4,9 and 3;
those numbers now inside this array like this
array[0] = 4;
array[1] = 9;
array[2] = 3;
1 2 3 4 5 6 7 8 9 10 11 12
|
for(int i=0;i<arraySize-1;i++)
{
for(int j=i;j<arraySize;j++)
{
if(array[i]<array[j])
{
int tmpVar = array[i];
array[i] = array[j];
array[j] = tmpVar;
}
}
}
| |
This code is technic of sorting called
bubble sort
The first for loop will goes from 0 to 1(because we have only 3 numbers remember)
this means that array[i] will take either 4 or 9;
the first for's period array[i] takes number 4 ,then compare it with 4,9 and 3
array[i]=4 <
array[j]=4 skeeps the if statement
array[i]=4 <
array[j]=9 this time the content of if statement will be excuted
array[i] exchange its value with array[j] mean that array[i] = 9 and array[j] = 4
array[i]=9 <
array[j]=3 skeeps the if statement
the second for's period array[i]=4;
array[i]=4 <
array[j]=4 skeeps the if statement
array[i]=4 <
array[j]=3 skeeps the if statement
well now
array[0] = 9;
array[1] = 4;
array[2] = 3;
the last code just shows those number by order
1 2 3 4
|
for(int i=0;i<arraySize;i++)
{
cout << array[i] << endl;
}
| |
hope I express well