How to pick 2 random digits from a number in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
 
int main(void) {
    int num = 213859;
    char str[6];
 
    sprintf(str,"%d", num);
 
    int size = strlen(str);
   
    srand((unsigned int)time(NULL));
   
    int digit2, digit1 = str[rand() % (size - 1)] - '0';
    
    do {
        digit2 = str[rand() % (size - 1)] - '0';
    } while (digit1 == digit2);
        
   
    printf("%d %d", digit1, digit2);
  
    return 0;
}
  
  
  
/*
run:
    
8 2
    
*/

 



answered Feb 3, 2024 by avibootz

Related questions

1 answer 181 views
1 answer 121 views
1 answer 197 views
1 answer 143 views
1 answer 174 views
1 answer 147 views
...