Write a code (using arrays) that reads a column of real numbers, records the hig
ID: 3849846 • Letter: W
Question
Write a code (using arrays) that reads a column of real numbers, records the highest and lowest values and what their positions are in the column of numbers (i.e., the highest number is 12 and it was the fourth number listed), and outputs those results (largest number and its position and smallest number and its position) in an organized, clear manner. Have your code determine how many numbers are given (not by reading a value of n, but by counting how many numbers there are before it hits a blank cell), and output this number as well.Explanation / Answer
c++ code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
//string filename = "input.txt";
string filename;
cout << "Enter the filename!" << endl;
cin >> filename;
string line;
ifstream myfile (filename.c_str());
if (myfile.is_open())
{
vector< int > tokens;
while ( getline (myfile,line) )
{
string buf; // Have a buffer string
stringstream ss(line); // Insert the string into a stream
// Create vector to hold our words
while (ss >> buf)
{
tokens.push_back(atoi(buf.c_str()));
}
}
myfile.close();
cout << "Total numbers are: " << tokens.size() << endl;
int minn = tokens[0];
int maxx = tokens[0];
int minindex = 0; int maxindex = 0;
for (int i = 0; i < tokens.size(); ++i)
{
if(tokens[i] > maxx)
{
maxx = tokens[i];
maxindex = i;
}
if (tokens[i] < minn)
{
minn = tokens[i];
minindex = i;
}
}
cout << "Maximum number found = " << maxx << " And this number was found at location " << maxindex + 1 << endl;
cout << "Minimum number found = " << minn << " And this number was found at location " << minindex + 1 << endl;
}
else
{
cout << "Unable to open file" << endl;
exit(1);
}
return 0;
}
input.txt
3 4 6 1 5 2 1
Sample Output:
Total numbers are: 7
Maximum number found = 6 And this number was found at location 3
Minimum number found = 1 And this number was found at location 4
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.