How to generate a random color in RGB format with C++

3 Answers

0 votes
#include <iostream>
#include <cstdlib>
#include <ctime>

#define SIZE 3

void generateRandomRGB(int rgb[]) {
   for (int i = 0; i < SIZE; i++) {
       rgb[i] = rand() % 256; // Generate values between 0 and 255
   }
}

int main() 
{
    int rgb[SIZE] = { 0 };
   
    srand(time(0)); 

    generateRandomRGB(rgb);
   
    std::cout << "Random RGB Color: rgb(" << rgb[0] << ", " << rgb[1] << ", " << rgb[2] << ")\n";
}


/*
run:

Random RGB Color: rgb(36, 93, 180)

*/

 



answered Oct 8, 2025 by avibootz
0 votes
#include <iostream>
#include <random>
  
int generateRandomNumber(int min, int max) {
    // Use a random device to seed the random number generator
    std::random_device rd;
 
    std::mt19937 gen(rd()); 
    std::uniform_int_distribution<> dis(min, max);
 
    return dis(gen);
}
  
// Function to generate a random RGB color
void generateRandomRGBColor() {
    // Generate random values for Red, Green, and Blue channels
    int red = generateRandomNumber(0, 255);
    int green = generateRandomNumber(0, 255);
    int blue = generateRandomNumber(0, 255);
  
    // Print the RGB color
    std::cout << "Random RGB Color: rgb(" << red << ", " << green << ", " << blue << ")\n";
}
  
int main() {
    generateRandomRGBColor();
}
  
  
/*
run:
  
Random RGB Color: rgb(35, 130, 134)
  
*/

 



answered Oct 8, 2025 by avibootz
edited Aug 22 by avibootz
0 votes
#include <iostream>
#include <random>

/*
    Generate a random color in RGB format: rgb(R, G, B)
    This program demonstrates how numbers and bits are used
    to produce valid 8‑bit channel values.
*/

/**
 * Create a random 8‑bit integer (0–255).
 * Uses C++'s <random> library for high‑quality randomness.
 */
unsigned int randomChannel() {
    // 8 bits → values from 0 to 255
    static std::random_device rd;
    static std::mt19937 gen(rd());
    static std::uniform_int_distribution<unsigned int> dist(0, 255);

    return dist(gen);
}

/**
 * Produce a random RGB color by combining the channels.
 */
std::string generateRandomRGB(unsigned int &rOut,
                              unsigned int &gOut,
                              unsigned int &bOut) {
    rOut = randomChannel();  // Red channel (8 bits)
    gOut = randomChannel();  // Green channel (8 bits)
    bOut = randomChannel();  // Blue channel (8 bits)

    // Construct the CSS-style RGB string
    return "rgb(" + std::to_string(rOut) + ", "
                 + std::to_string(gOut) + ", "
                 + std::to_string(bOut) + ")";
}

int main() {
    unsigned int r, g, b;
    std::string rgb = generateRandomRGB(r, g, b);

    std::cout << "Red (8 bits): " << r << "\n";
    std::cout << "Green (8 bits): " << g << "\n";
    std::cout << "Blue (8 bits): " << b << "\n";
    std::cout << "RGB color: " << rgb << "\n";
}


/*
run:

Red (8 bits): 193
Green (8 bits): 106
Blue (8 bits): 110
RGB color: rgb(193, 106, 110)

*/

 



answered Aug 22 by avibootz
...