How to create a list of random HEX RGB color codes in C++

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// Function to generate a random number between min and max (inclusive)
int generateRandomNumber(int min, int max) {
    return rand() % (max - min + 1) + min;
}

// Function to generate a random RGB color as a hex string
void generateRandomColor(char *color) {
    int red = generateRandomNumber(0, 255);
    int green = generateRandomNumber(0, 255);
    int blue = generateRandomNumber(0, 255);

    // Format as #RRGGBB
    sprintf(color, "#%02X%02X%02X", red, green, blue);
}

int main() {
    int total = 5;

    if (total <= 0) {
        fprintf(stderr, "Invalid size. Please enter a positive integer.\n");
        return 1;
    }

    // Seed the random number generator
    srand((unsigned int)time(NULL));

    printf("Generated Random Colors:\n");

    for (int i = 0; i < total; ++i) {
        char color[8]; // for "#RRGGBB" + null terminator
        generateRandomColor(color);
        printf("%s\n", color);
    }

    return 0;
}



/*
run:

Generated Random Colors:
#39A16E
#BE0AC8
#9E8BEC
#3AEA96
#86A809

*/

 



answered 4 hours ago by avibootz

Related questions

...