-3

How can I generate a random number with a specified length in c? I have to ask the user for a specified length for two sequences and based off of that responses I generate 2 random numbers of those lengths.

Please enter 2 max lengths for your sequences: 3 6

Seq1:
456
seq2
937123
Peter O.
  • 32,158
  • 14
  • 82
  • 96
  • 1
    https://stackoverflow.com/questions/1202687/how-do-i-get-a-specific-range-of-numbers-from-rand – 0x6261627564 Dec 04 '19 at 06:12
  • 2
    Does this answer your question? [How do I get a specific range of numbers from rand()?](https://stackoverflow.com/questions/1202687/how-do-i-get-a-specific-range-of-numbers-from-rand) – matb Dec 04 '19 at 06:18
  • Please do your own research before posting the question. – PunyCode Dec 04 '19 at 06:51
  • Are long sequences required? If so, you may need to generate each digit separately and store them in an array. – Ian Abbott Dec 04 '19 at 11:49

1 Answers1

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

int main(void) 
{ 
    int l,max=1,min=0;
    printf("Please enter the length:  "); 
    scanf("%d",&l); 

    srand(time(0)); 
    while(l>0){
        max*=10;
        l--;
    }
    min=max/10;
    printf(" %d ", min + rand() % (max - min));

    return 0; 
} 

srand()is used to return different random value at every compilation.

You can modify it for two inputs accordingly.

Saksham Chaudhary
  • 519
  • 1
  • 4
  • 14
  • 2
    Your code specifies a max length while the question ask for a specific length. What is not specified is if the random number may start with the digit 0. If yes, your code is correct and `min=0`. Otherwise `min=max/10`. You must not decrement `max`. It is an error in your code. – chmike Dec 04 '19 at 10:41
  • You are correct @chmike, i have edited the post. Thank you so much for your valuable contribution. – Saksham Chaudhary Dec 05 '19 at 17:51