**Discussion 3** 09/08, 09/10 [(back to course webpage)](./mcs360_fall2020.html) # Problem 1 Write a CPP program that asks the user to input a number $n$, and then input $n$ integers $a_0,\ldots,a_{n-1}$. Store these integers in a `std::vector` object. Then, find the largest number in the integers. ## Example Run: ``` Enter n: 5 Enter the integers: 100 200 30 50 70 The largest integer is: 200 ``` ## Hints
Hint 1 This is how you would take the input: ~~~~~~~~cpp int main() { int n; std::cout << "Enter n: "; std::cin >> n; std::vector a; std::cout << "Enter the integers: "; int inp; for(int i = 0; i < n; i++) { std::cin >> inp; a.push_back(inp); } // Find the largest! return 0; } ~~~~~~~~~ Now your job is to figure out an algorithm to compute the largest entry!
Hint 2 We can find the largest in the array by the following algorithm: ********************************************************************************************************************************************** *|100|200| 30| 50| 70| |100|200| 30| 50| 70| |100|200| 30| 50| 70| |100|200| 30| 50| 70| * * ^ ^ ^ ^ * * | -> | -> | -> ... -> | * * i=0 i=1 i=2 i=4 * * (initial) (100 < 200) (200 > 30) (200 > 70) * * l=100 l=200 l=200 l=200 * **********************************************************************************************************************************************
## Solution
Solution ~~~~~~~~~~cpp #include #include int main() { int n; std::cout << "Enter n: "; std::cin >> n; std::vector a(n); // same thing as saying int a[n]; std::cout << "Enter the integers: "; for(int i = 0; i < n; i++) { std::cin >> a[i]; } // Find the largest! int largest = a[0]; for(int i=1; i < n; i++) { if(largest < a[i]) { largest = a[i]; } } // Is it possible to find the largest in less than n number of primitive steps? // The answer is no: you have to at least loop through all the elements of the array // once, otherwise it's impossible to figure out the largest of them. std::cout << "The largest integer is: " << largest << std::endl; return 0; } ~~~~~~~~~~~~
Remark There is also a standard library function called `std::max_element` in `algorithm.h` that lets you do this in a click, but it does exactly what we did here. Check [here](https://www.cplusplus.com/reference/algorithm/max_element/) for the details.
# Problem 2 Write a CPP program that populates an `std::vector` with 100 random numbers, each ranging from 0 to 9 (both inclusive). Print the elements of the vector. Find the element with the highest frequency in the vector. ## Hints
Hint 1 You can look up the rolling die problem done in lecture. It tells you how to compute the frequency of every element.