I need to add a code that allows the user to type in any number from 1 to 10 and it will print how many times that number is in the array. I don't know how to go about this.
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
srand(unsignedint(time(nullptr))); // Initialise random number generator
int array[100] {0};
for (int j = 0; j < 100; ++j)
array[j] = rand() % 10 + 1; // Numbers 1 - 10
//Print Array
for (int i = 0; i < 100; ++i)
std::cout << array[i] << ' ';
std::cout << '\n';
int num;
std::cout << "Enter a number between 1 and 10: ";
std::cin >> num;
// Assumes num is correct - no range checking etc!
int cnt = 0;
for (int i = 0; i < 100; ++i)
cnt += array[i] == num; // True is 1, false is 0
std::cout << "That number was found " << cnt << " times\n";
}
#include <iostream>
#include <random>
#include <array>
#include <algorithm>
std::mt19937 rng(std::random_device {}());
int main() {
constexpr size_t noElems { 100 };
std::uniform_int_distribution<int> distrib(1, 10);
std::array<int, noElems> array;
for (auto& a : array)
std::cout << (a = distrib(rng)) << ' ';
std::cout << '\n';
int num {};
// Assumes num is correct - no error, range checking etc!
std::cout << "\nEnter a number between 1 and 10: ";
std::cin >> num;
std::cout << "That number was found " << std::ranges::count(array, num) << " times\n";
}
depending on your requirements & attitude, you may also get the user's choice first and count them as they come in, which gets rid of needing the array at all (unless you use it again after the fact). That may defeat the purpose of the problem, to learn about C arrays maybe (?), so its on you to know what your lessons were about and the theme and whether that is a useful shortcut or one that prevents working with your current material.
Also, if you do need/want the array, you can print the random numbers as assigned (as per my second code) rather than having a separate loop just to display.
But as jonnin says, all this depends upon the exercise requirements.
If you don't need the array, then possibly something like:
#include <iostream>
#include <random>
#include <algorithm>
std::mt19937 rng(std::random_device {}());
int main() {
constexpr size_t noElems { 100 };
std::uniform_int_distribution<int> distrib(1, 10);
int num {}, cnt {};
// Assumes num is correct - no error, range checking etc!
std::cout << "Enter a number between 1 and 10: ";
std::cin >> num;
for (size_t i {}; i < noElems; ++i) {
constauto r { distrib(rng) };
std::cout << r << ' ';
cnt += r == num;
}
std::cout << "\n\nThat number was found " << cnt << " times\n";
}