In: Computer Science
**I need to make this program to make sure that the numbers are unique. In another word, if the number has been generated and appear early, it should continue to find the next number until the number is unique.
Hint: use the array to check whether the number has been generated.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL));
int n, low, high;
cout << "Enter how many random numbers you would like to see: ";
cin >> n;
cout << "Enter the lower limit now: ";
cin >> low;
cout << "And now enter the higher limit: ";
cin >> high;
cout << n << " random numbers:";
for (int i = 0; i < n; ++i) {
cout << " " << low + (rand() % (high-low+1)) << endl;
}
cout << endl;
return 0;
}
Please show me how it can be done and explain code needed if possible. Thanks!
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand(time(NULL)); int n, low, high; cout << "Enter how many random numbers you would like to see: "; cin >> n; int *arr = new int[n]; cout << "Enter the lower limit now: "; cin >> low; cout << "And now enter the higher limit: "; cin >> high; int r, k = 0; bool found; for(int i = 0;k<n;i++){ found = false; r = low + (rand() % (high-low+1)); // Checking whether new random value r already exists in the array arr for(int j = 0;j<k;j++){ if(arr[j]==r){ found=true; break; } } // If not found then adding r to arr if(!found){ arr[k++] = r; } } // Printing the random array cout << n << " random numbers:"; for (int i = 0; i < n; ++i) { cout << " " << arr[i] << endl; } cout << endl; return 0; }