The Wayback Machine - https://web.archive.org/web/20240808004751/https://www.geeksforgeeks.org/program-generate-random-alphabets/
Open In App

Program to generate random alphabets

Last Updated : 24 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Prerequisite : rand() and srand() 

Given all alphabets in a character array, print a string of random characters of given size.
We will use rand() function to print random characters. It returns random integer values. This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. 

  1. A ubiquitous use of unpredictable random characters is in cryptography, which underlies most of the schemes which attempt to provide security in modern communications (e.g. confidentiality, authentication, electronic commerce, etc).
  2. Random numbers are also used in situations where “fairness” is approximated by randomization, such as selecting jurors and military draft lotteries.
  3. Random numbers have uses in physics such as electronic noise studies, engineering, and operations research. Many methods of statistical analysis, such as the bootstrap method, require random numbers.

Pseudo code : 

  1. First we initialize two character arrays, one containing all the alphabets and other of given size n to store result.
  2. Then we initialize the seed to current system time so that every time a new random seed is generated.
  3. Next, we use for loop till n and store random generated alphabets. 

Below is C++ implementation of above approach :

C++




// CPP Program to generate random alphabets
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 26;
  
// Returns a string of random alphabets of
// length n.
string printRandomString(int n)
{
    char alphabet[MAX] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g',
                          'h', 'i', 'j', 'k', 'l', 'm', 'n', 
                          'o', 'p', 'q', 'r', 's', 't', 'u',
                          'v', 'w', 'x', 'y', 'z' };
  
    string res = "";
    for (int i = 0; i < n; i++) 
        res = res + alphabet[rand() % MAX];
      
    return res;
}
  
// Driver code
int main()
{
   srand(time(NULL));
   int n = 10;
   cout << printRandomString(n);
   return 0;
}


Java




// JAVA Program to generate random alphabets
import java.util.*;
  
class GFG
{
  
static int MAX = 26;
  
// Returns a String of random alphabets of
// length n.
static String printRandomString(int n)
{
    char []alphabet = { 'a', 'b', 'c', 'd', 'e', 'f', 'g',
                        'h', 'i', 'j', 'k', 'l', 'm', 'n', 
                        'o', 'p', 'q', 'r', 's', 't', 'u',
                        'v', 'w', 'x', 'y', 'z' };
  
    String res = "";
    for (int i = 0; i < n; i++) 
        res = res + alphabet[(int) (Math.random() * 100 % MAX)];
      
    return res;
}
  
// Driver code
public static void main(String[] args)
{
    int n = 10;
    System.out.print(printRandomString(n));
}
}
  
// This code is contributed by Rajput-Ji


C#




// C# Program to generate random alphabets
using System;
  
class GFG
{
static int MAX = 26;
  
// Returns a String of random alphabets of
// length n.
static String printRandomString(int n)
{
    char []alphabet = { 'a', 'b', 'c', 'd', 'e', 'f', 'g',
                        'h', 'i', 'j', 'k', 'l', 'm', 'n', 
                        'o', 'p', 'q', 'r', 's', 't', 'u',
                        'v', 'w', 'x', 'y', 'z' };
  
    Random random = new Random();
    String res = "";
    for (int i = 0; i < n; i++) 
        res = res + alphabet[(int)(random.Next(0, MAX))];
      
    return res;
}
  
// Driver code
public static void Main()
{
    int n = 10;
    Console.Write(printRandomString(n));
}
}


Javascript




<script>
// JAVAscript Program to generate random alphabets
let MAX = 26;
  
// Returns a String of random alphabets of
// length n.
function printRandomString(n)
{
    let alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g',
        'h', 'i', 'j', 'k', 'l', 'm', 'n',
        'o', 'p', 'q', 'r', 's', 't', 'u',
        'v', 'w', 'x', 'y', 'z'];
  
    let res = "";
    for (let i = 0; i < n; i++)
    {
        res = res + alphabet[(Math.floor(Math.random() * 10) % MAX)];
    }
  
    return res;
}
  
// Driver code
let n = 10;
document.write(printRandomString(n));
  
// This code is contributed by gfgking.
</script>


Python3




# Python program to generate random alphabets
  
import random
  
# Returns a string of random alphabets of length n.
def printRandomString(n):
    MAX = 25
    alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g',
                'h', 'i', 'j', 'k', 'l', 'm', 'n',
                'o', 'p', 'q', 'r', 's', 't', 'u',
                'v', 'w', 'x', 'y', 'z']
    res = ""
    for i in range(n):
        res = res + alphabet[random.randint(0, MAX)]
    return res
  
  
n = 10
print(printRandomString(n))
  
# This code is contributed by lokeshmvs21.


Output

urdfwootzr

Time Complexity: O(n)

Auxiliary Space: O(26)

This program will print different characters every time we run the code



Similar Reads

Generate a string with maximum possible alphabets with odd frequencies
Given an integer N, the task is to generate a string str which contains maximum possible lowercase alphabets with each of them appearing an odd number of times.Examples: Input: N = 17 Output: bcdefghijklmnopqr Explanation: In order to maximize the number of characters, any 17 characters can be selected and made to appear once. Thus, abcdefghijklmno
6 min read
C++ program to generate random number
The below implementation is to generate random number from 1 to given limit. The below function produces behavior similar to srand() function. Prerequisite : random header in C++ | Set 1(Generators) // C++ program to generate random number #include &lt;bits/stdc++.h&gt; using namespace std; // Function with return random number from 1 to // given l
1 min read
Implement random-0-6-Generator using the given random-0-1-Generator
Given a function random01Generator() that gives you randomly either 0 or 1, implement a function that utilizes this function and generate numbers between 0 and 6(both inclusive). All numbers should have same probabilities of occurrence. Examples: on multiple runs, it gives 3 2 3 6 0 Approach : The idea here is to find the range of the smallest numb
5 min read
Test Case Generation | Set 2 ( Random Characters, Strings and Arrays of Random Strings)
Set 1 (Random Numbers, Arrays and Matrices) Generating Random Characters C/C++ Code // A C++ Program to generate test cases for // random characters #include&lt;bits/stdc++.h&gt; using namespace std; // Define the number of runs for the test data // generated #define RUN 5 // Define the range of the test data generated // Here it is 'a' to 'z' #def
11 min read
Generate random String of given size in Java
Given a size as n, The task is to generate a random alphanumeric String of this size. Below are various ways to generate random alphanumeric String of given size: Prerequisite : Generating random numbers in Java Method 1: Using Math.random() Here the function getAlphaNumericString(n) generates a random number of length a string. This number is an i
3 min read
Generate a random permutation of 1 to N
Given an integer N, the task is to generate N non-repeating random numbers. Examples: Input: N = 5 Output: 1 5 2 4 3 Input: N = 8 Output: 7 2 1 8 3 6 4 5 Approach: Create an array of N elements and initialize the elements as 1, 2, 3, 4, ..., N then shuffle the array elements using Fisher-Yates shuffle Algorithm. Fisher–Yates shuffle Algorithm works
13 min read
Generate a random permutation of elements from range [L, R] (Divide and Conquer)
Given a range [L, R] where L ? R, the task is to generate a random permutation of the sequence [L, L + 1, L + 2, ..., R].Examples: Input: L = 5, R = 15 Output: 11 9 6 5 8 7 10 12 13 15 14Input: L = 10, R = 20 Output: 16 14 11 10 13 12 15 17 18 20 19 Approach: We will use Divide and Conquer algorithm for our solution. We will create a global vector
7 min read
How to generate a vector with random values in C++?
Vectors are dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. It can also be created with random value using the generate function and rand() function. Below is the template of both the STL functions: Syntax: int rand(void): It retu
2 min read
Generate a random Binary String of length N
Given a positive integer N, the task is to generate a random binary string of length N. Examples: Input: N = 7Output: 1000001 Input: N = 5Output: 01001 Approach: The given problem can be solved by using the rand() function that generates a random number over the range [0, RAND_MAX] and with the help of the value returned by this function, any numbe
5 min read
Generate N Random Hexadecimal Numbers
Given a positive integer N, the task is to generate N random hexadecimal integers. Examples: Input: N = 3Output:F9AD0D9E19B24CD01A5E Approach: The given problem can be solved with the help of the rand() function which is used to generate random integers. A character array can be created which stores all the possible characters in the hexadecimal no
5 min read
Practice Tags :
three90RightbarBannerImg