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,854 questions

51,775 answers

573 users

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

1 Answer

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

// Function to get random three consecutive digits from a 6-digit number
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");  // error message
        return;
    }

    int start = rand() % 4;  // Random start index (0–3)
    strncpy(out, s + start, 3);
    out[3] = '\0';  // null-terminate
}

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

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

    getRandomThreeDigits(num, randomThreeDigits);

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

    return 0;
}

 
  
   
/* 
run:
   
Random three consecutive digits: 234
 
*/

 



answered Nov 25, 2025 by avibootz
...