You are here:

C++/random effect

Advertisement


Question
Hi,
I am curnetly learning C++, and I wanted to create a program that would generate random letters. There seems to be a problem, I have the right letters but in the same order. I wanted to know how to input the "random" effect.

//my code right now
#include<iostream.h>
#include<stdlib.h>
#include<time.h>
void Scramble(char * Array, int iLength);
void main()
{
srand((unsigned int)time(NULL));
int x;
int y;
char chLetter[20];
int i;
char ch;
for (i=0, ch='A'; i<20; i++, ch++)
{
 chLetter[i] = ch;
}
for (i=0; i<20; i++)
{
 cout << chLetter[i] << " ";
}
cout << endl;
cout << "Scrambled:" << endl;
Scramble(chLetter, 20);
for (i=0; i<20; i++)
{
 cout << chLetter[i] << " ";
}
cout << endl;

cout << "Scrambled again:" << endl;
Scramble(chLetter, 20);
for (i=0; i<20; i++)
{
 cout << chLetter[i] << " ";
}
cout << endl;
/*
cin >> y;
cout << "\n\n";
while(y=1)
{
cout << x;
break;
}
x=rand()%20;
*/
}
void Scramble(char * Array, int iLength)
{
}
//end

Waiting for your reply,
Avinash Nayak  

Answer
Avinash Nayak , Thank you for your question.

One way to select a random letter is to generate a random number in the range 0 through 25. Use this number as the subscript to fetch the letter from the character string containing all letters "abcd...xyz".

David Spector

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


David Spector

Expertise

Highly knowledgeable in the C++ language, Visual C++ (MSVC), Windows API, documentation and other quality-assurance techniques, and debugging. Knowledgeable in MFC, COM, GUI design, and object-oriented design.

Experience

I have been a software engineer since 1965. I have been published. My specializations have been: biomedical programming, compiler implementation, and many kinds of Windows programming. I don't do Databases or other business-oriented stuff.

Publications
Windows?/DOS Developer's Journal, ACM SIGPLAN Notices, and Computer Science Press.

Education/Credentials
ICCP Systems Programming Certification
Master's degree equivalent in Computer Science

©2016 About.com. All rights reserved.