Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Program to generate random lowercase letter
In C#, you can generate a random lowercase letter using the Random class and ASCII character conversion. This technique generates a random number between 0 and 25, then converts it to a corresponding lowercase letter from 'a' to 'z'.
Syntax
Following is the syntax for generating a random lowercase letter −
Random random = new Random();
int randomIndex = random.Next(0, 26);
char randomLetter = (char)('a' + randomIndex);
How It Works
The process involves three key steps:
-
Generate random number:
random.Next(0, 26)produces a number from 0 to 25 -
Add to 'a': Adding this number to the ASCII value of 'a' (97) gives us ASCII values 97-122
-
Cast to char: Converting the result back to
chargives us letters 'a' through 'z'
Using Random Class for Single Letter
Example
using System;
class Demo {
static void Main() {
Random random = new Random();
// Generate random lowercase letter
int a = random.Next(0, 26);
char ch = (char)('a' + a);
Console.WriteLine("Random lowercase letter: " + ch);
}
}
The output of the above code is −
Random lowercase letter: t
Using Method to Generate Multiple Letters
Example
using System;
class Demo {
static char GenerateRandomLowercase() {
Random random = new Random();
int randomIndex = random.Next(0, 26);
return (char)('a' + randomIndex);
}
static void Main() {
Console.WriteLine("Generating 5 random lowercase letters:");
for (int i = 0; i
The output of the above code is −
Generating 5 random lowercase letters:
Letter 1: m
Letter 2: k
Letter 3: r
Letter 4: b
Letter 5: x
Using Single Random Instance
For better performance when generating multiple random letters, create one Random instance and reuse it −
Example
using System;
class Demo {
static void Main() {
Random random = new Random();
Console.WriteLine("Random string of 8 lowercase letters:");
string randomString = "";
for (int i = 0; i
The output of the above code is −
Random string of 8 lowercase letters:
hfkjwqpn
Conclusion
Generating random lowercase letters in C# involves using the Random.Next(0, 26) method to get a number between 0-25, then adding it to the ASCII value of 'a' and casting to char. This technique is useful for creating random passwords, test data, or any application requiring random character generation.
