# Random password generator in C

In this article, we will delve into an interesting and practical problem related to string manipulation in C programming. We are going to build a "Random Password Generator" in C. This problem not only enhances your understanding of string manipulation but also your knowledge of the C Standard Library.

## Problem Statement

The task is to build a program that generates a random password of a specified length. The password should include uppercase and lowercase alphabets, digits, and special characters.

## C Solution Approach

To solve this problem, we'll leverage the power of the C Standard Library. We'll use the rand() function to generate random numbers within a specified range. We'll create a string of all possible characters that our password can contain, and then for each character in our password, we'll randomly select a character from this string.

### Example

Here's the C code that implements a random password generator −

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

char possibleChars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#\$%^&*()";

srand(time(0)); // seed for random number generation
for(int i = 0; i < len; i++) {
int randomIndex = rand() % (sizeof(possibleChars) - 1);
}

password[len] = '\0'; // null terminate the string
}

int main() {
int len = 10; // desired length of password
return 0;
}


### Output

The randomly generated password is: )^a3cJciyk


## Explanation with a Test Case

Let's say we want to generate a password of length 10.

When we pass this length to the generate Password function, it generates a random password with 10 characters.

The function constructs a string of all possible characters that the password can contain. Then it uses the rand() function to generate a random index, which is used to pick a character from the string of possible characters. It repeats this process for the specified length of the password.

Please note that each time you run this program, it will generate a different password due to the random nature of our algorithm.

## Conclusion

This problem presents an interesting use case of random number generation and string manipulation in C. It's a fantastic problem to understand and practice how to use the C Standard Library effectively.

Updated on: 18-May-2023

629 Views