Write a complete C++ program that reads in an array of type int. The program pro
ID: 3684174 • Letter: W
Question
Write a complete C++ program that reads in an array of type int. The program provides facility to either read an array from the keyboard or from a file, at the user's choice. If the user chooses file input, the program should request a file name. You may assume that there are less than 100 entries in this array. Your program determines how many entries there are. In addition, the program should also find the maximum number in the array and calculates the average of the array. You are required to use functions.
Explanation / Answer
#include <iostream>
#include <fstream>
using namespace std;
void Keyboard(int *pNum, int *pCount); //case 1
void CountNums(int *pNum, int **pCount, int count);
int FindHighestNum(int *pNum, int count);
int main()
{
int *pNum = NULL;
int *pCount = NULL;
int i = 3;
while (i != 0)
{
cout << "Hi Welcome To the System " << endl;
cout << "Do you want to input the numbers from a file or from the keyboard? " << endl;
cout << "1) Keyboard." << endl;
cout << "2) File." << endl;
cout << "Enter 1 or 2 or 0 to exit.";
cin >> i;
switch (i)
{
case 0:
return 0;
break;
case 1:
Keyboard(pNum, pCount);
break;
case 2:
break;
default:
break;
};
}
return 0;
}
void Keyboard(int *pNum, int *pCount)
{
int count = 0;
cout << "How many numbers to be put in ? (up to 50)";
cin >> count;
if (count > 50)
count = 50;
pNum = new int[count];
cout << "Enter the numbers:" << endl;
for (int i = 0; i < count; i++)
{
cout << i+1 << ": ";
cin >> pNum[i];
}
CountNums(pNum, &pCount, count);
for (int j = 0; j < (FindHighestNum(pNum, count)+1); j++)
{
if (pCount[j] > 0)
cout << j << ": " << pCount[j] << endl;
}
}
void CountNums(int *pNum, int **pCount, int count)
{
(*pCount) = new int[FindHighestNum(pNum, count)+1];
for (int j = 0; j <= FindHighestNum(pNum, count); j++)
(*pCount)[j] = 0;
for (int i = 0; i < count; i++)
(*pCount)[pNum[i]]++;
}
int FindHighestNum(int *pNum, int count)
{
int highnum = 0;
for (int i = 0; i < count; i++)
{
if (pNum[i] > highnum)
highnum = pNum[i];
}
return highnum;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.