Introduction
In this tutorial, we will demonstrate how to write a C program that displays a random quote from a predefined list of quotes.
This program uses basic features of the C programming language such as arrays, the rand()
function, and simple control structures.
The purpose of this program is to give you a practical example of how to generate random output, which can be useful in many applications.
Objective
The objective of this program is to generate a random quote from a list of quotes each time it is run. The program will:
- Define a list of motivational or inspirational quotes.
- Use the
rand()
function to select a random quote. - Display the selected quote on the screen.
Code
#include #include #include int main() { // Define an array of quotes const char *quotes[] = { "The only way to do great work is to love what you do. - Steve Jobs", "Success is not the key to happiness. Happiness is the key to success. - Albert Schweitzer", "Don't watch the clock; do what it does. Keep going. - Sam Levenson", "The best time to plant a tree was 20 years ago. The second best time is now. - Chinese Proverb", "It always seems impossible until it's done. - Nelson Mandela" }; // Initialize random number generator srand(time(NULL)); // Generate a random index int randomIndex = rand() % 5; // Since there are 5 quotes // Display the random quote printf("Random Quote: \n%s\n", quotes[randomIndex]); return 0; }
Explanation
The program begins by defining an array of quotes. Each quote is stored as a string in the array quotes[]
.
We use the rand()
function to generate a random index from the array. The expression rand() % 5
ensures that the random number will be between 0 and 4, which corresponds to the indices of the quotes array.
The srand(time(NULL))
statement initializes the random number generator with the current time, ensuring that the random sequence differs each time the program runs.
Finally, the selected quote is printed to the console using printf()
.
How to Run the Program
- Write the C code in a text editor (such as Notepad++ or Visual Studio Code) and save the file with a
.c
extension (e.g.,random_quote.c
). - Open a terminal or command prompt window.
- Navigate to the directory where you saved your C program file.
- Compile the program using a C compiler. If you’re using GCC, the command is:
gcc random_quote.c -o random_quote
- Run the compiled program:
./random_quote
- You should now see a random quote displayed in your terminal or command prompt window.