Für Vorlesungen, bitte die Webseite verwenden. https://flavigny.de/lecture
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
2.0KB

  1. #include "cpp_headers/fcpp.hh"
  2. int main() {
  3. print("Please enter 10 natural numbers, enter 0 to show the sorted array, -1 to quit");
  4. // initialize the array with 0s
  5. int numbers[10] = {0,0,0,0,0,0,0,0,0,0};
  6. // ask 11 times for input
  7. for (int i = 0; i < 11; i++) {
  8. int input = enter_int("> ");
  9. // quit on -1
  10. if (input == -1) {
  11. break;
  12. // print the array on 0
  13. } else if (input == 0) {
  14. printf("Array = [");
  15. for (int n = 0; n < 10; n++) {
  16. // last number is printed with trailing bracket and newline
  17. if (n == 9) {
  18. printf("%d]\n", numbers[n]);
  19. // print out a single number with trailing space
  20. } else {
  21. printf("%d ", numbers[n]);
  22. }
  23. }
  24. break;
  25. // if already full, quit
  26. } else if (i >= 10) {
  27. print("array already full, terminating");
  28. break;
  29. // quit on invalid input
  30. } else if (input < -1) {
  31. print("input not allowed, terminating");
  32. break;
  33. // otherwise insert new input
  34. } else {
  35. // set last number to new input
  36. numbers[i] = input;
  37. // sort numbers from 0 to i
  38. for (int k = 0; k < i; k++) {
  39. // whenever we see a wrong ordered number
  40. if (numbers[k] > numbers[k+1]) {
  41. int smaller = numbers[k+1];
  42. int bigger = numbers[k];
  43. // flip the numbers
  44. numbers[k] = smaller;
  45. numbers[k+1] = bigger;
  46. // and step back to compare with previous numbers
  47. if (k <= 1) {
  48. // there is no number before the first one
  49. k = 0;
  50. } else {
  51. // step back 2, because we are adding 1 each time
  52. k = k-2;
  53. }
  54. }
  55. }
  56. }
  57. }
  58. }