C++ language only, please. (In simple terms) 14. Student Line Up A teacher has a
ID: 3724370 • Letter: C
Question
C++ language only, please. (In simple terms)
14. Student Line Up A teacher has asked all her students to line up according to their first name. For exam- ple, in one class Amy will be at the front of the line, and Yolanda will be at the end. Write a program that prompts the user to enter the number of students in the class, then loops to read that many names. Once all the names have been read, it reports which student would be at the front of the line and which one would be at the end of the line. You may assume that no two students have the same name. Input Validation: Do not accept a number less than 1 or greater than 25 for the number of students.Explanation / Answer
14. C++ Code:
#include<iostream>
using namespace std;
int main()
{
int n;
//get no. of students
cout<<"Enter no. of students (1-25): ";
cin>>n;
//validate
while(n<1 || n>25)
{
cout<<"Enter no. of students (1-25): ";
cin>>n;
}
//get names
cout<<"Enter names"<<endl;
int i;
string name, first, last;
//first name
cin>>name;
first = last = name;
//read all names
for(i=1;i<n;i++)
{
cin>>name; //get name
//if greater, assign it to last
if(name.compare(last)>0)
last = name;
//if lesser, assign it to first
else if(name.compare(first)<0)
first = name;
}
//print result
cout<<endl;
cout<<"Front of the line: "<<first<<endl;
cout<<"At the end of the line: "<<last<<endl;
return 0;
}
25. C++ Code: Keep .cpp file and names.txt in same folder
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream inFile("names.txt"); //open file
string name, first, last;
//first name
getline(inFile, name);
first = last = name;
//read all names
while(getline(inFile, name))
{
//if greater, assign it to last
if(name.compare(last)>0)
last = name;
//if lesser, assign it to first
else if(name.compare(first)<0)
first = name;
}
//print result
cout<<endl;
cout<<"Front of the line: "<<first<<endl;
cout<<"At the end of the line: "<<last<<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.