/* ************************************************************************** * Program name : 021_Random_Numbers (Version 1.00) * * Author : Duck Wong * * Language : C / C++ * * Compiler : Boodshed Dec-C++ compiler Ver 3.95 * * Computer : PII350 * * O/S : Windows 98 * ************************************************************************** * Version 1.00 : 2000/06/11 - first version * ************************************************************************** * Description : (a) Asking the number of set * * (b) Asking the number of numbers in each set * * (c) Asking the smallest value * * (d) Asking the largest value * * (e) Draw random numbers * * (f) Try again ? * ************************************************************************** */ #include #include #include #include int main() { // part 1 : declaration int Index_1, Index_2, Num_Of_sets, Member, Max, Min; char Again; do { // part 2 : Repeat asking the number of set do { cout << "How many set of numbers do you want (1-10) ? "; cin >> Num_Of_sets; } while (Num_Of_sets < 1 || Num_Of_sets > 10 ); // part 3 : Repeat asking the number of numbers in each set do { cout << "How many numbers in each set do you need (1-10) ? "; cin >> Member; } while (Member < 1 || Member > 10 ); // part 4 : Repeat asking the smallest value do { cout << "The lower limit (smallest value) is ? "; cin >> Min; } while (Min < 1 ); // part 5 : Repeat asking the largest value do { cout << "The upper limit (largest value) is ? "; cin >> Max; } while (Max <= Min ); // part 6 : Draw random numbers srand(time(NULL)); // Note (1) for (Index_1=1; Index_1<=Num_Of_sets; Index_1++) // Note (2) { cout << "\n\tSet " << setw(2) << Index_1 << " : "; for (Index_2=1; Index_2<=Member; Index_2++) // Note (3) cout << setw(5) << Min + (rand() % (Max-Min+1)); // Note (4) } cout << "\n\n"; // part 7 : try again ? cout << "\n\t\aTry again (Y/N) : "; cin >> Again; cout << "\n"; } while (Again=='Y' || Again=='y'); cout << "\n" << endl; system("PAUSE"); return 0; } /* Notes (1) srand(time(NULL)); (acts as the keyword Randomize in PASCAL) This statement causes the computer to read its clock to obtain the value for seed automatically. Thus different sequence of random numbers is obtained each time the program is run. (2) Use Num_Of_sets to control number of lines (3) Use Member to control the number of random numbers listed per each line (4) When using the function rand, the width of the range is determined by the number used to scale rand with the modulus operator, and the starting number of the range is equal to the number that is added. Example : Let's say Min is 3 and Max is 10 , then Min + (rand() % (Max-Min+1)) = 3 + (rand() % (10 -3 +1)) = 3 + (rand() % 8) will generate number from 3 to 10. */