×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object 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 [Last updated : February 27, 2023]

Problem statement

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.

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

#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

Solution Explanation

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.

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.