Creating an array with random letters

i have created this program but getting random numbers how do i get random letters instead of numbers.


#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;

const int N = 5, M = 5;

void printArray(int x[N][M])
{
for (int r = 0; r<N; r++) {
for (int c = 0; c<M; c++)
cout << x[r][c] << " ";
cout << endl;
}
}

int main()
{
int A[N][M];
srand(time(0));

for (int r = 0; r<N; r++)
for (int c = 0; c<M; c++)
A[r][c] = rand() % 100;
printArray(A);
cout << endl;

printArray(A);

system("pause");
return 0;
}
Last edited on
Cast your numbers to a char. For example:

char a = 65;

Stores the character representation of 65 (which is an 'A') into the variable a. There are multiple ways to cast data types. Google it. There is lot's of tutorials there.
Last edited on
First of all, please learn to use tags, it'll make your code easier to read
http://www.cplusplus.com/articles/z13hAqkS/

As for the code, you'll want to typecast the output as char, like this
cout<< (char) x[r][c] << " ";
You'll also want to replace the rand() % 100;
with rand() % 25+65
im still kind of confused. isnt there a way where i have to program generate random letters. like right im getting random numbers generated between 1 and 100.
I don't think there is really any way to generate random characters, but typecasting random numbers as chars should be enough.
Thank You HOWDOIAIM.
1
2
3
4
5
    char A[N][M];
    
    for (int r = 0; r<N; r++)
        for (int c = 0; c<M; c++)
            A[r][c] = rand() % ('z' - 'a' + 1) + 'a';


The expression ('z' - 'a' + 1) evaluates to 26, which is the number of letters in the alphabet. I wrote it that way to show how to use it in other cases. Say you wanted to generate letters from 'M' to 'P', you could write rand() % ('P' - 'M' + 1) + 'M';
Topic archived. No new replies allowed.