How to create an array with random HEX RGB color codes in C

1 Answer

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

#define TOTAL 5
#define COLOR_LENGTH 8  // "#RRGGBB" + null terminator

// 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() {
    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));

    char colors[TOTAL][COLOR_LENGTH];

    for (int i = 0; i < TOTAL; ++i) {
        generateRandomColor(colors[i]);
    }

    printf("Generated Random Colors:\n");
    for (int i = 0; i < TOTAL; ++i) {
        printf("%s\n", colors[i]);
    }

    return 0;
}



/*
run:

Generated Random Colors:
#1DF00B
#0F52B6
#7C5DC1
#42D1D5
#B20267

*/

 



answered 4 hours ago by avibootz

Related questions

...