60 lines
2.0 KiB
C++
60 lines
2.0 KiB
C++
#include "cpp_headers/fcpp.hh"
|
|
|
|
int main() {
|
|
print("Please enter 10 natural numbers, enter 0 to show the sorted array, -1 to quit");
|
|
// initialize the array with 0s
|
|
int numbers[10] = {0,0,0,0,0,0,0,0,0,0};
|
|
// ask 11 times for input
|
|
for (int i = 0; i < 11; i++) {
|
|
int input = enter_int("> ");
|
|
// quit on -1
|
|
if (input == -1) {
|
|
break;
|
|
// print the array on 0
|
|
} else if (input == 0) {
|
|
printf("Array = [");
|
|
for (int n = 0; n < 10; n++) {
|
|
// last number is printed with trailing bracket and newline
|
|
if (n == 9) {
|
|
printf("%d]\n", numbers[n]);
|
|
// print out a single number with trailing space
|
|
} else {
|
|
printf("%d ", numbers[n]);
|
|
}
|
|
}
|
|
break;
|
|
// if already full, quit
|
|
} else if (i >= 10) {
|
|
print("array already full, terminating");
|
|
break;
|
|
// quit on invalid input
|
|
} else if (input < -1) {
|
|
print("input not allowed, terminating");
|
|
break;
|
|
// otherwise insert new input
|
|
} else {
|
|
// set last number to new input
|
|
numbers[i] = input;
|
|
// sort numbers from 0 to i
|
|
for (int k = 0; k < i; k++) {
|
|
// whenever we see a wrong ordered number
|
|
if (numbers[k] > numbers[k+1]) {
|
|
int smaller = numbers[k+1];
|
|
int bigger = numbers[k];
|
|
// flip the numbers
|
|
numbers[k] = smaller;
|
|
numbers[k+1] = bigger;
|
|
// and step back to compare with previous numbers
|
|
if (k <= 1) {
|
|
// there is no number before the first one
|
|
k = 0;
|
|
} else {
|
|
// step back 2, because we are adding 1 each time
|
|
k = k-2;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|