In: Computer Science
How do I use ASCII code to generate and display two random letters that are one lowercase and one uppercase in C++?
Please give me an example.
//To generate letters from ASCII value. First, we need to get the values for the alphabets Uppercase and Lowercase
//Uppercase 'A' has ASCII value 65........ 'Z' has the value 90.
//Lowercase 'a' has value 97........ 'z' has the value 122.
//so in order to generate random uppercase and lowercase characters we need to generate random values of the above range and then typecasting it to char type while in the cout statement.
NOTE: the values are compiler dependent and rand() function may cause error then include stdlib.h
--------------------------------------------------------------------------code-------------------------------------------------------------------------------------
#include <iostream>
using namespace std;
int main()
{
int u_max=90,u_min=65; //declaring upper and lower
range for uppercase letter
int l_max=122,l_min=97; //declaring range for lower
case letter
//calculating a random int value in the range of upper case letters
int random_upper = (rand() %(u_max + 1 - u_min)) +
u_min;
//calculating a random int value for lower case letter
int random_lower = (rand() %(l_max + 1 - l_min)) +
l_min;
//printing both the letters by typecasting inti char type
cout<<"Random uppercase letter for ASCII value
"<<random_upper<<" :
"<<(char)random_upper<<endl;
cout<<"Random lowercase letter for ASCII value
"<<random_lower<<" :
"<<(char)random_lower<<endl;
return 0;
}