/*
* This function does not find the first occurrence of the desired index in general,
* at the moment it shows the index of the array element that is located immediately after the array element that is greater than the desired value.
* Moreover, it does not even show the index, but the position, that is, the index + 1.
* In order for it to find the first occurrence of the element, the cycle must be rewritten in this form.
* for (pos = 0; pos < current_length; pos++)
* {
* if (a[pos] == val)
* {
* found = true;
* break;
* }
* }
*/
#include <iostream>
using namespace std;
int findFirst(int a[], int current_length, int val)
{
bool found = false;
int pos;
for (pos = 0; pos < current_length && !found; pos++)
{
if (a[pos] > val)
{
found = true;
}
}
if (found)
return pos;
else
return -1;
}
int main()
{
int a[5] = { 1, -1, 1, 6, 7 };
cout << "Initial array: ";
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;
cout << "First position of 1 is: " << findFirst(a, 5, 1) << endl;
system("pause");
return 0;
}
Comments
Leave a comment