fork download
  1. #include <iostream>
  2. #include <cstdlib> // For rand() and srand()
  3. #include <ctime> // For time()
  4.  
  5. int main() {
  6. const int SIZE = 10;
  7. int arr[SIZE];
  8.  
  9. // Seed the random number generator
  10. std::srand(std::time(0));
  11.  
  12. // Fill the array with random numbers in the interval [-10, 10]
  13. for (int i = 0; i < SIZE; ++i) {
  14. arr[i] = std::rand() % 21 - 10; // Generates numbers from 0 to 20, then shifts to -10 to 10
  15. }
  16.  
  17. // Display the array
  18. std::cout << "Array elements: ";
  19. for (int i = 0; i < SIZE; ++i) {
  20. std::cout << arr[i] << " ";
  21. }
  22. std::cout << std::endl;
  23.  
  24. // Find the maximum and minimum elements and their indices
  25. int maxElement = arr[0];
  26. int minElement = arr[0];
  27. int maxIndex = 0;
  28. int minIndex = 0;
  29.  
  30. for (int i = 1; i < SIZE; ++i) {
  31. if (arr[i] > maxElement) {
  32. maxElement = arr[i];
  33. maxIndex = i;
  34. }
  35. if (arr[i] < minElement) {
  36. minElement = arr[i];
  37. minIndex = i;
  38. }
  39. }
  40.  
  41. // Display the results
  42. std::cout << "Maximum element: " << maxElement << " at index " << maxIndex << std::endl;
  43. std::cout << "Minimum element: " << minElement << " at index " << minIndex << std::endl;
  44.  
  45. return 0;
  46. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
Array elements: 6 -1 7 7 2 9 -1 7 6 8 
Maximum element: 9 at index 5
Minimum element: -1 at index 1