In: Computer Science
Asks the user "How many parrots do you own?"
2: Reads in that many single word names (one for each parrots) from the user and stores the names in an array.
3: After the user has finished entering names, the program should display the list of all the parrots the user entered.
4: then display the parrots in alphabetical order for part 3. Note: string objects can be compared with the “<” operator, which will determine if a given string is alphabetically less than another string.
You may assume the user will own at most 100 parrots.
c++
"output"
Welcome! How many dogs do you own?
- 4
Ok, enter the names!
> james
> flyingmo
> homer
> kitty
these are the names you entered: flyingmo, homer, james, kitty
Dear student,
The solution to the above problem statement using C++ programming language is as follows:
CODE:
#include <iostream>
using namespace std;
void swap(string *x, string *y) //used to swap values between two positions in an array
{
string temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int numPar;
cout<<"Hello, How many parrots do you own?\n";
cin>>numPar;
string parNames[numPar];
for(int i=0;i<numPar;i++) //loop to take input from user one by one
{
cin>>parNames[i];
}
//Now we will use bubble sorting technique to sort the names
int x = sizeof(parNames)/sizeof(parNames[0]);
for (int i = 0; i < x-1; i++)
{
for (int j = 0; j < x-i-1; j++)
{
if (parNames[j] > parNames[j+1])
swap(&parNames[j], &parNames[j+1]); //calls the swap function defined above
}
}
cout<<"The names entered by you in ascending order are:\n";
for(int i=0;i<numPar;i++)
{
cout<<parNames[i]<<"\n";
}
return 0;
}
-------------------------------------------------------------------------------------------------------------------------------------------------
SAMPLE OUTPUT:
-------------------------------------------------------------------------------------------------------------------------------------------------
I hope the given solution helps clear your doubt.
Don't forget to give it a thumbs up.
Regards