the problem is to take 5 integer inputs from user and store them in an array.
Let's start declaring an array that can hold up to 5 integers.
int numbers[5] = {};
// ^^^ This should be the size of the array, not the maximum index
Since C++11, you can use a proper standard container
std::array<int, 5> numbers{};
Note that in both snippet I initialized those arrays.
Now, the loop that reads all the elements of the array can be written as
for (int i = 0; i < 5; ++i) {
// ^
}
Or use a ranged for
for (auto & number : numbers)
{ // ^^^^^^^^ Loops through the array using `number` as a reference to each element
std::cin >> number;
if (!std::cin) {
std::cerr << "An error occurred while reading.\n";
break;
}
}
The posted loop also goes from 0 to 4 (included), but the array declared in that snippet only has 4 elements, so that it is accessed out of bounds and the program has undefined behaviour.
Another problem, is that the program doesn't check
whether that number is present in array or not
It does only one "check", instead of a loop:
if ( num[i] = comp) {
num[i] = comp
is an assignment, not a comparison (you should adequately rise your compiler warning level) and an assignment to an element outside the array (i
has value 5, now). It's the result of this assignment, comp
, that is used as a condition, which means that the branch is executed whenever comp
is not 0.
Or, at least, this is the most likely outcome, given that that assignment is UB too and the compiler could genereate whatever code it decides or your program could seg-fault due to that access out of bounds.