Code:
#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>
int main()
{
int i,j;
double a[9];
printf ("This program determines the middle value\n");
printf ("of nine real numbers that you enter from the keyboard\n");
for (i = 0; i < 9; i++)
{
printf ("%d: ", i);
scanf("%lg", &a[i]);
}
// Print the numbers
printf ("You entered:\n");
for (i = 0; i < 9; i++)
{
printf ("%d: %lg\n", i, a[i]);
}
printf ("\n\n");
// Sort the array
for (i = 0; i < 8; i++)
{
for (j = i+1; j < 9; j++)
{
if (a[j] < a[i])
{
// Exchange them
double temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
printf ("Sorted array:\n");
for (i = 0; i < 9; i++)
{
printf ("%d: %lg\n", i, a[i]);
}
printf ("\n\n");
printf ("The middle value is %lg\n", a[4]);
getchar();
getchar();
return 0;
}
I don't understand the part about sorting the array. I know I am misunderstanding it, but I have been trying to understand it for quite some time and its not making sense to me.
For example: Say these are my array values
a[0]=5
a[1]=3
a[2]=2
a[3]=1
a[4]=7
a[5]=8
a[6]=9
a[7]=2
a[8]=3
This is how I am interpreting the program:
Is a[1] < a[0]? If so, switch them.
Since a[0] = 5 and a[1] = 3 this is true. Thus, I switch them and get:
a[0] = 3 and a[1] = 5.
Then i and j are both incremented to get the following:
is a[2] < a [1]? If so switch them.
a[1] is now 5, correct? Thus, a[1] IS larger than a[2]. So we switch them.
a[1] = 2 and a[2] = 5.
I continued, but there is already a problem here.
So far the array is a[0]=3, a[1] = 2, and a[2] = 5.
This is not sorted already from low to high. How exactly is this program taking values from a[8] for example and comparing them with a[2]?
I am just having trouble understanding this. I apologize for the long post, but I would really appreciate it if anyone can tell me exactly whats going on.
Thanks!
-Frankie