In: Computer Science
Create a vector of 100 integers PRG from 1 to 500. Find the max and min and print those out. Please use c++.
In case of any query do comment. Please rate answer as well. Thanks
Code:
#include <iostream>
#include <vector> //for vector
#include <stdlib.h> //for rand function
#include <time.h>
using namespace std;
int main()
{
vector<int> numbers;
int number, max, min;
srand (time(NULL)); //initilize the seed for random number generation
for (int i = 0; i < 100; i++)
{
number = rand() % 500 + 1; // rand() % 500 will generate number between 0 to 499 hence adding 1 to generate between 1 to 500
numbers.push_back(number);
}
max = numbers[0];
min = numbers[0];
//iterate over vector to find min and max
for(int i = 1; i < numbers.size(); i++) //start iterating from the second element
{
//if curent number is less than min then set the min to curent number
if(numbers[i] < min)
{
min = numbers[i];
}
//if curent number is greater than max then set max to current number
if(numbers[i] > max)
{
max = numbers[i];
}
}
//display the result
cout << "Max: " << max << endl;
cout << "Min: " << min << endl;
return 0;
}
==========screen shot of the code ==========
output: