In: Computer Science
In C++, Create an array of 10 characters. Use a loop to prompt
for 10 letters (a-z|A-Z) and store each in the array. If an invalid
character is entered, re-prompt until a valid char is
entered.
After 10 characters are stored in the array, use a loop to print
out all characters in the array from the first to the last element.
Then, use another loop starting at the last element to print all
characters in the array in reverse order. Finally, print out pairs
of the elements starting with the first and last element and
traversing towards the middle of the array.
Example:
1.: A 2.: B 3.: C 4.: D 5.: E 6.: F 7.: G 8.: H 9.: I 10.: J Forward: A, B, C, D, E, F, G, H, I, J Backward: J, I, H, G, F, E, D, C, B, A Pairs: A, J, B, I, C, H, D, G, E, F
Source Code:
Output:
Code in text format (See above images of code for indentation):
#include <iostream>
using namespace std;
/*main function*/
int main()
{
/*Array declaration*/
char a[10];
int i;
/*read characters from user*/
cout<<"Enter characters
(a-z|A-Z)"<<endl;
for(i=0;i<10;i++)
{
cout<<i+1<<".: ";
cin>>a[i];
/*input validation*/
while(isalpha(a[i])==false)
{
/*read
again*/
cout<<i+1<<".: ";
cin>>a[i];
}
}
/*print array in forward*/
cout<<"\nForward: ";
for(i=0;i<9;i++)
cout<<a[i]<<", ";
/*last element without comma*/
cout<<a[i]<<endl;
/*print array in reverse*/
cout<<"Backward: ";
for(i=9;i>0;i--)
cout<<a[i]<<", ";
/*last element with no comma*/
cout<<a[i]<<endl;
/*print array in pairs*/
cout<<"Pairs: ";
for(i=0;i<4;i++)
cout<<a[i]<<",
"<<a[10-i-1]<<", ";
/*last pair with no comma at end*/
cout<<a[i]<<", "<<a[10-i-1];
return 0;
}