Answer to Question #201448 in C++ for shuvo

Question #201448
Read the following function:
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;
}
Does the above function always find the correct position of the first occurrence of a given
integer value in an array, if the integer value exists in the array
1
Expert's answer
2021-06-02T06:02:50-0400
/*
* 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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog