Write a program to generate a random single-digit number.
Example 1: 7
Example 2: 3
Approach: To solve the problem, follow the below idea:
To generate a random single-digit number, we can first generate a random integer and then take apply modulo to get the last digit of that random integer. This last digit can be the random single digit number.
Step-by-step algorithm:
- Generate a random integer.
- Take modulo 10 of the random integer to get a single digit random number.
Below is the implementation of the algorithm:
C++
#include <iostream> #include <cstdlib> #include <ctime> using namespace std;
int main() {
srand ( time (NULL));
int randomDigit = rand () % 10;
cout << randomDigit << endl;
return 0;
} |
C
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() {
srand ( time (NULL));
int randomDigit = rand () % 10;
printf ( "%d\n" , randomDigit);
return 0;
} |
Java
import java.util.Random;
public class RandomDigit {
public static void main(String[] args) {
Random random = new Random();
int randomDigit = random.nextInt( 10 );
System.out.println(randomDigit);
}
} |
Python3
import random
random_digit = random.randint( 0 , 9 )
print (random_digit)
|
C#
using System;
class Program {
static void Main() {
Random random = new Random();
int randomDigit = random.Next(0, 10);
Console.WriteLine(randomDigit);
}
} |
Javascript
const randomDigit = Math.floor(Math.random() * 10); console.log(randomDigit); |
Output
8
Time Complexity: O(1) as the time complexity of generating a random number is constant.
Auxiliary Space: O(1)
Article Tags :
Recommended Articles