Skip to content
Related Articles

Related Articles

Random password generator in C
  • Difficulty Level : Medium
  • Last Updated : 20 Jan, 2021

In this article, we will discuss how to generate a random password of a given length consists of any characters.

Approach:

  • The below-given program involves basic concepts like variables, data types, array, loop, etc.
  • Follow the below steps to solve this problem:
    • Take the length of the password and declare a character array of that length to store that password.
    • Declare character array of all the capital letters, small letters, numbers, special characters.
    • Now according to the program below, respective if-else gets executed and a random password gets generated.

Below is the program of the above approach:

C

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program for the above approach
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
  
// Function to randomly generates password
// of length N
void randomPasswordGeneration(int N)
{
    // Initialize counter
    int i = 0;
  
    int randomizer = 0;
  
    // Seed the random-number generator
    // with current time so that the
    // numbers will be different every time
    srand((unsigned int)(time(NULL)));
  
    // Array of numbers
    char numbers[] = "0123456789";
  
    // Array of small alphabets
    char letter[] = "abcdefghijklmnoqprstuvwyzx";
  
    // Array of capital alphabets
    char LETTER[] = "ABCDEFGHIJKLMNOQPRSTUYWVZX";
  
    // Array of all the special symbols
    char symbols[] = "!@#$^&*?";
  
    // Stores the random password
    char password[N];
  
    // To select the randomizer
    // inside the loop
    randomizer = rand() % 4;
  
    // Iterate over the range [0, N]
    for (i = 0; i < N; i++) {
  
        if (randomizer == 1) {
            password[i] = numbers[rand() % 10];
            randomizer = rand() % 4;
            printf("%c", password[i]);
        }
        else if (randomizer == 2) {
            password[i] = symbols[rand() % 8];
            randomizer = rand() % 4;
            printf("%c", password[i]);
        }
        else if (randomizer == 3) {
            password[i] = LETTER[rand() % 26];
            randomizer = rand() % 4;
            printf("%c", password[i]);
        }
        else {
            password[i] = letter[rand() % 26];
            randomizer = rand() % 4;
            printf("%c", password[i]);
        }
    }
}
  
// Driver Code
int main()
{
    // Length of the password to
    // be generated
    int N = 10;
  
    // Function Call
    randomPasswordGeneration(N);
  
    return 0;
}

chevron_right


Output:

51WAZMT?Z$


Time Complexity: O(N)
Auxiliary Space: O(26)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :