Rewrite the following program using functions, so that your main will look like
ID: 3566565 • Letter: R
Question
Rewrite the following program using functions, so that your main will look like below, and CAPACITY is declared as a global constant.
#include <iostream>
/** input numbers terminating with 'q'
* find the largest OR the smallest element, dependingf on the user's choice
* outputs the numbers with an arrow indicating the largest or the smallest
*/
using namespace std;
int main(){
const int CAPACITY = 1000;
double values[CAPACITY];
int current_size = 0;
cout << "Please enter values, Q to quit:" << endl;
double input;
while (cin >> input){
if (current_size < CAPACITY){
values[current_size] = input;
current_size++;
}
}
cin.clear();
cin.ignore();
cout << "Would you like to find (1) The Largest? or (2) The Smallest ";
cout << "Enter 1 or 2: ";
int choice;
cin >> choice;
double result = values[0];
for (int i = 1; i < current_size; i++){
if (choice == 1){ // if looking for largest
if (values[i] > result)
result = values[i];
}
else if (values[i] < result) // if looking for smallest
result = values[i];
}
cout << " The values are: ";
for (int i = 0; i < current_size; i++){
cout << values[i];
if (values[i] == result)
if (choice==1)
cout << " <== largest value";
else
cout << " <== smallest value";
cout << endl;
}
}
Explanation / Answer
#include <iostream>
using namespace std;
const int CAPACITY = 1000;
int current_size = 0;
void getvalues(double* values )
{
double input;
cout << "Please enter values, Q to quit:" << endl;
while (cin >> input)
{
if (current_size < CAPACITY)
{
values[current_size] = input;
current_size++;
}
}
}
double find_largest(double values[])
{
double result = values[0];
for(int i = 0 ; i < current_size; i++)
if(values[i] > result)
result = values[i];
return result;
}
double find_smallest(double values[])
{
double result = values[0];
for(int i = 0 ; i < current_size; i++)
if(values[i] < result)
result = values[i];
return result;
}
void printvalues(double values[])
{
cout << " The values are: ";
for (int i = 0; i < current_size; i++)
cout << values[i] << " ";
}
int main()
{
double values[CAPACITY];
getvalues(values);
printvalues(values);
cout << "Would you like to find (1) The Largest? or (2) The Smallest ";
cout << "Enter 1 or 2: ";
cin.clear();
cin.ignore(255, ' ');
int choice;
cin >> choice;
switch(choice)
{
case 1:
cout << "The largest number in the array is " << find_largest(values) << endl;
break;
case 2:
cout << "The smallest number in the array is " << find_smallest(values) << endl;
break;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.