Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,970 questions

51,912 answers

573 users

How to select random three digits from anywhere in a 6-digit number in C

1 Answer

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

// Function to shuffle digits and return 3 random digits
void getRandomThreeDigits(int num, char *out) {
    char s[16];  // buffer to hold number as string
    sprintf(s, "%06d", num);  // ensure it's 6 digits (pad with zeros if needed)

    if (strlen(s) != 6) {
        strcpy(out, "Err");
        return;
    }

    // Shuffle
    for (int i = 5; i > 0; i--) {
        int j = rand() % (i + 1);
        char tmp = s[i];
        s[i] = s[j];
        s[j] = tmp;
    }

    // Copy first 3 characters after shuffle
    strncpy(out, s, 3);
    out[3] = '\0';  // null terminate
}

int main(void) {
    srand((unsigned)time(NULL));  // Seed random generator

    int num = 123456;  // Example 6-digit number
    char randomThree[4];  // buffer for 3 digits + null terminator

    getRandomThreeDigits(num, randomThree);

    printf("Random three digits: %s\n", randomThree);

    return 0;
}

  
   
/* 
run:
   
Random three digits: 251
 
*/

 



answered Nov 25, 2025 by avibootz
...