In: Computer Science
Create a vector of 50 characters PRG from A to Z. Sort the list in reverse order (from Z to A). Please use c++. Please use #include<iostream>. Please don't use the ASCII values.
Please find below the code, code screenshots and output screenshots. Please refer to the screenshot of the code to understand the indentation of the code. Please get back to me if you have any concerns. Else please upvote.
Code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<char> a; // Declaring the vector
int random_character; //Variable to store the random character generated
//initiale an alphabet array
char alphabet[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' };
//initialize random seed
srand (time(NULL));
//Populate the vector with random numbers between 1 and 500
for(int i = 0; i<50; i++){
random_character = alphabet[rand() % 26]; //generate the random character
a.push_back(random_character); //add the random character generated to vector
}
// Print the vector before sorting
cout << "The Vector before sorting is as follows: \n";
for (int i = 0; i < a.size(); i++) { //loop through each elements in vector
cout << a[i] << " "; //display the vector content
}
//sorting the vector
for(int i=0; i<a.size()-1; i++){
for(int j=0; j<a.size()-i-1;j ++){
if(a[j]<a[j+1]) //compare the adjacent items in vector
{
//swap the elements
char temp = a[j];
a[j] = a[j+1];
a[j+1]=temp;
}
}
}
// Print the vector after sorting
cout << "\n\nThe Vector after sorting is as follows: \n";
for (int i = 0; i < a.size(); i++) { //loop through each elements in vector
cout << a[i] << " "; //display the vector content
}
return 0;
}
Output: