/* This program demonstrates * 1. Random number Generation * 2. Working with numbers and digits * 3. Introduction to arrays * Random Number generation. * We can use the rand() function in the cstdlib library to generate a random * number. It will return an integer. We can set an upper limit by calling the * random function and then using the modulus on the returned value. * We can set a lower limit by adding the lower limit to the value returned by * the function. * * Arrays * An array is a collection of variables that satisfies the following properties: * 1. All the variables in the array are of the same type. * 2. All the variables share the same name and are accessed by an index. * 3. The elements (individual variables) are ordered and start at index 0. * 4. The elements are in continuous memory locations. * */ #include #include #include //for the rand() function using namespace std; int main() { // The rand() function generates a random integer btween 0 and 2^31 cout << rand() << endl; int init; cout << "Enter a seed value for the RNG: "; cin >> init; /* The srand() function initializes the RNG. If we do not initialize it, * it would generate the same sequence of numbers each time. * Here, we ask the user for a number, and initialize the RNG with the * user entered value. Conventionally, we use the system time, but we don't * do that here, since different platforms need different libraries for that. */ srand(init); int low = 25, high = 120; // generate 10 random numbers in a range - low => 15, high => 120 // rand() % (high - low) + low for (int i = 0; i < 10; i++) cout << rand() % (high - low) + low << endl; int num; cout<<"Enter a number: "; cin>>num; /* to count the number of digits in a number: * We keep dividing by 10. Every time we do that, we remove the last digit. * If the number is not 0, then there are more digits, so count 1 digit. * Repeat until the number becomes 0 */ int numDigits = 0; while(num != 0) { numDigits ++; num = num / 10; } cout<<"Number of digits: "<< numDigits<>array[i]; } cout<<"Enter the element at index 4: "; cin>>array[4]; return 0; }