fork download
  1. // Elaine Torrez CS1A Chapter 7, Arrays
  2. /**********************************************************************************************
  3. * LARGEST & SMALLEST (10) *
  4. *---------------------------------------------------------------------------------------------*
  5. * This program asks the user to enter 10 real numbers, stores them in an array, echoes the *
  6. * input back to the user, and then reports the largest and the smallest value entered. *
  7. * *
  8. * Algorithm (high level): *
  9. * 1) Read 10 numbers into an array. *
  10. * 2) Echo the numbers back to the user. *
  11. * 3) Initialize largest and smallest to the first element. *
  12. * 4) Scan through the rest of the array, updating largest/smallest as needed. *
  13. * 5) Display the results. *
  14. * *
  15. * INPUT *
  16. * numbers[10] : Ten user-entered real numbers *
  17. * *
  18. * OUTPUT *
  19. * Echo of the 10 numbers entered *
  20. * Largest value *
  21. * Smallest value *
  22. **********************************************************************************************/
  23. #include <iostream>
  24. using namespace std;
  25.  
  26. int main() {
  27. const int SIZE = 10; // number of values
  28. double numbers[SIZE]; // array to store user input
  29. double largest, smallest;
  30.  
  31. // Ask the user for 10 numbers
  32. cout << "Enter 10 numbers: ";
  33. for (int i = 0; i < SIZE; i++) {
  34. cin >> numbers[i];
  35. }
  36. // Show back what the user entered
  37. for (int i = 0; i < SIZE; i++)
  38. cout << numbers[i] << " ";
  39. cout << endl;
  40.  
  41. // Assume first element is both largest and smallest at first
  42. largest = numbers[0];
  43. smallest = numbers[0];
  44.  
  45. // Loop through array to find largest and smallest
  46. for (int i = 1; i < SIZE; i++) {
  47. if (numbers[i] > largest)
  48. largest = numbers[i];
  49. if (numbers[i] < smallest)
  50. smallest = numbers[i];
  51. }
  52.  
  53. // Display results
  54. cout << "Largest value: " << largest << endl;
  55. cout << "Smallest value: " << smallest << endl;
  56.  
  57. return 0;
  58. }
  59.  
Success #stdin #stdout 0.01s 5320KB
stdin
8 7 6 5 4 3 2 1 2 2 
stdout
Enter 10 numbers: 8 7 6 5 4 3 2 1 2 2 
Largest value: 8
Smallest value: 1