Introduction
The Random Quote Generator program is designed to display a random quote from a pre-defined list of inspirational quotes. This program showcases the usage of arrays, random number generation, and basic input-output operations in C++. It is a simple, yet effective example of how to work with arrays and randomization in C++ programming.
Objective
The primary objective of this program is to demonstrate how to store multiple strings (quotes) in an array and select one at random to display to the user. It also introduces the use of the rand()
function to generate random numbers, and the srand()
function to seed the random number generator for variability.
C++ Code
#include #include #include using namespace std; int main() { // Array of quotes string quotes[] = { "The best way to predict the future is to create it. - Abraham Lincoln", "In the middle of difficulty lies opportunity. - Albert Einstein", "What lies behind us and what lies before us are tiny matters compared to what lies within us. - Ralph Waldo Emerson", "Success is not final, failure is not fatal: It is the courage to continue that counts. - Winston Churchill", "You miss 100% of the shots you don't take. - Wayne Gretzky" }; // Number of quotes int numQuotes = sizeof(quotes) / sizeof(quotes[0]); // Seed the random number generator srand(static_cast(time(0))); // Generate a random index int randomIndex = rand() % numQuotes; // Display the random quote cout << "Random Quote: " << quotes[randomIndex] << endl; return 0; }
Explanation of the Program Structure
This program begins by including necessary libraries: iostream
for input-output operations, cstdlib
for the rand()
and srand()
functions, and ctime
for seeding the random number generator with the current time.
It then declares an array of strings, quotes
, which contains five motivational quotes. The program calculates the number of quotes using sizeof(quotes) / sizeof(quotes[0])
, which divides the total size of the array by the size of one element in the array.
Next, the random number generator is seeded using srand(time(0))
, ensuring that the program generates a different random index each time it is run.
The program then generates a random index between 0 and the number of quotes using rand() % numQuotes
and displays the corresponding quote to the user using cout
.
How to Run the Program
To run this program, follow these steps:
- Ensure you have a C++ compiler installed on your machine, such as GCC or MinGW.
- Create a new file with the extension
.cpp (e.g.,
random_quote_generator.cpp
) and paste the code into the file. - Open a terminal or command prompt and navigate to the directory where the file is saved.
- Compile the program using the following command:
g++ random_quote_generator.cpp -o random_quote_generator
- Run the program by executing the following command:
./random_quote_generator
Each time you run the program, a different random quote will be displayed.