Open In App

Program to generate a random two-digit number

Last Updated : 18 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Write a program to generate a random two-digit number.

Example 1: 73
Example 2: 26

Approach: To solve the problem, follow the below idea:

We can generate a random two-digit number by generating a random integer first and then modulo it by 90. Now, after modulo 90 the remainder can be in the range 0 to 89, so in order to have the remainder as a two-digit number, we can further add 10 to make the range 10 to 99.

Step-by-step algorithm:

  • Seed the random number generator to ensure different random numbers on each run.
  • Generate a random number within the range of two-digit numbers (10 to 99).

Below is the implementation of the algorithm:

C++




#include <cstdlib>
#include <ctime>
#include <iostream>
 
using namespace std;
 
int main()
{
    // Seed the random number generator with the current
    // time
    srand(time(0));
    // Generate a random two-digit number
    int randomNumber = rand() % 90 + 10;
    cout << "Generated Random Number: " << randomNumber
         << endl;
    return 0;
}


C




#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main()
{
    srand(time(0)); // Seed the random number generator with
                    // the current time
    int randomNumber
        = rand() % 90
          + 10; // Generate a random two-digit number
    printf("Generated Random Number: %d\n", randomNumber);
    return 0;
}


Java




import java.util.Random;
 
public class RandomNumberGenerator {
    public static void main(String[] args)
    {
        Random rand = new Random();
        int randomNumber
            = rand.nextInt(90)
              + 10; // Generate a random two-digit number
        System.out.println("Generated Random Number: "
                           + randomNumber);
    }
}


Python3




import random
 
 
def main():
    # Generate a random two-digit number
    random_number = random.randint(10, 99)
    print(f"Generated Random Number: {random_number}")
 
 
if __name__ == "__main__":
    main()


C#




using System;
 
class Program {
    static void Main()
    {
        Random rand = new Random();
        int randomNumber = rand.Next(
            10, 100); // Generate a random two-digit number
        Console.WriteLine("Generated Random Number: "
                          + randomNumber);
    }
}


Javascript




function generateRandomNumber() {
    let randomNumber = Math.floor(Math.random() * 90) + 10;  // Generate a random two-digit number
    console.log("Generated Random Number: " + randomNumber);
}
 
generateRandomNumber();


Output

Generated Random Number: 47

Time Complexity: O(1), it takes constant time to generate a random number.
Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads