Home » C++ programs » C++ Most popular & searched programs

C++ program to generate random alphabets and store them into a character array

In this program first we take two character arrays, one to store all the alphabets and other to print random characters into it. To keep it simple we have taken the length as 20.
Submitted by Abhishek Pathak, on May 25, 2017

Random is one of the most cumbersome concepts to understand in C++. Multiple functions with same name are sort of confusing even for experienced programmers. However, applying them correctly can be fun. Here is a simple program that will print the alphabets in a random manner.

Consider the program:



#include <iostream>
using namespace std;

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

int main()
{	
	char alphabets[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
	char rString[20];

	srand(time(NULL));

	int i=0;
	while(i<20) {
		int temp = rand() % 26;
		rString[i] = alphabets[temp];
		i++;
	}

	for(i=0; i<20; i++)
		cout<<rString[i];

	return 0;
}

Output

qaicgosutvmscsfufpfk

In this program first we take two character arrays, one to store all the alphabets and other to print random characters into it. To keep it simple we have taken the length as 20.

Now we initialize the seed to current system time so that every time a new random seed is generated.

Next, in the while loop, we loop through the length of the random string (20 here) and store random generated alphabets. We take a temp variable to generate a number between 0-26. Then we provide this number to alphabets array and a random string is generated.

After that we print the final random generated string.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.