Random Password Generator program in C++

Random Password Generator program in C++

This program will show how to create random password generator with required length in C++. It automatically generates a strong password containing lowercase alphabets, uppercase alphabets, numbers and special symbols.


using namespace std;
int main()
    int len,i,j;
    char lower[]= "abcdefghijklmnopqrstuvwxyz";
    char num[]= "0123456789";
    char symbols[]= "!@#$%&";
    string s="";    //to store random generated characters
    cout<<" Enter the length of password:";
        cout<<" Password length too short!";
    else if(len>50)
        cout<<" Password length too long!";
            cout<<" Generated strong password...\n Your new password is : ";
                s+=upper[rand()%26];    //random upper characters

                s+=lower[rand()%26];    //random lower characters

                s+=num[rand()%10];  //random numbers

                s+=symbols[rand()%6];   //random symbols

            int n=s.length();
            char password[n+1];
            strcpy(password,s.c_str()); //passing the string into array "password"

    for(i=n-1;i>0;i--)         //for shuffling the password generated
        int temp=password[i];
        password[i]= password[j];
        password[j]= temp;
    for(int i=0;i<n;i++)
        cout<<password[i];      //displaying password
return 0;

Outputs –

random password generator outputs

Explanation –

At first we declare 4 different arrays of uppercase, lowercase alphabets, numbers and symbols. This program uses ‘rand()’ function to choose characters randomly. For this <ctime> library is required. Further the number of characters to generate of each arrays are divided as- uppercase = length/3, lowercase= length – 3*(length/3), numbers = length/3 and symbols = length/3. So this distribution makes the password strong with all four in appropriate proportions. There is a ‘for’ loop for each array to generate random values. And those are concatenated to a blank string. So we require <string.h> too. After that the string is passed to a new array using ‘strcpy’ and ‘c_str()’ inbuilt functions. Finally we shuffle new array and display accordingly.


So those were the steps to make a random password generator in C++. The main concept is the use of random function. If you have any doubt, mention in the comment section. Also share it with your programming buddies and friends. For daily updates follow us on Instagram.

Also checkout: Tic-Tac-Toe in C++.

Visit again for more such programs!


Leave a Reply

Your email address will not be published. Required fields are marked *