C++ program to generate random alphabets


In this tutorial, we will be discussing a program to generate random alphabets.

For this, we will have a fixed size of array/string and use the rand() function to generate a random string of alphabets.

Example

#include <bits/stdc++.h>
using namespace std;
const int MAX = 26;
//generating a string of random alphabets
string gen_random(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;
}
int main(){
   srand(time(NULL));
   int n = 7;
   cout << gen_random(n) << endl;
   return 0;
}

Output

gwqrgpa
raja
Published on 03-Dec-2019 10:15:58
Advertisements