i have this exercise where i have to find the error in some code and correct it in some cases , i already did what i managed to figure out by myself but i still have this one code that i cant figure whats the error in it since am still new to the course and some of the consepts there are still new to me , thank you in advance .
notice : there are two errors in this code!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int search(int a[n], int numberUsed, int target)
{
int index = 0;
bool found = false;
while ((!found) && (index < numberUsed))
if (target = a[index])
found = true;
else
index++;
if (found)
return index;
elsereturn -1;
}
First, the indentation is awful, and is really detrimental to the readability of the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int search(int a[n], int numberUsed, int target)
{
int index = 0;
bool found = false;
while ((!found) && (index < numberUsed))
if (target = a[index])
found = true;
else
index++;
if (found)
return index;
elsereturn -1;
}
Once I stop focusing on the indentation, it becomes clear that = is being used in your condition on line 6 instead of ==.
Hello ganado ,i hope u re doing well, first i want to thank u for ur help and ur remark , i just edited it to make it clear
i forgot to mention that there are two errors in this code,
thank you again!
The only thing you did was double-space the code, and maybe change the indents a bit :) The indentation is still inconsistent. I already posted the better indentation excerpt, so no worries. <Edit: The indentation was since updated again, after I posted this.>
I don't see two errors in the code. The code could be simplified and perhaps guarded against future changes with more { } pairs inserted, the 'n' in the function signature is unnecessary and implies there is a global const n somewhere, using the variable name 'numberUsed' to mean the size of the search space of the array is questionable, but I don't see an obvious runtime problem except the = sign in the function alone.
#include <iostream>
using std::cout;
constint n = 42;
int search(int a[n], int numberUsed, int target)
{
int index = 0;
bool found = false;
while ((!found) && (index < numberUsed))
if (target == a[index])
found = true;
else
index++;
if (found)
return index;
elsereturn -1;
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << search(arr, 10, 5) << '\n';
}
But that 'n' being in the function signature is at best useless, and at worst, misleading.
It would be an error if there wasn't a definition of 'n' for the compiler to see. Since I do not have the full context of the program, it is impossible to determine whether or not the excerpt will compile without more information.