I wrote a basic linear search C ++ code whenever I run it, the result is always against the expected result it happens. For example, I want to find 4. In an array where it is present, it says that the number is not found, but after the discovery, an absent element can say that the element is found at position 0.
After seeing the code for one hour or so, I have not found any solution yet.
#include & lt; Iostream & gt; using namespace std; // scanning program intranet (int a [], int z, int n, int srch element) {for (int z = 0; zlt; n; z ++) {if (a [z] == srhalment) {Return Zed; }} Return -1; } // main program int main () {int i, n, a [1000], z; // Asking for the size of the array & lt; & Lt; "Scan the required array to scan:"; Cin & gt; & Gt; N; Cout & lt; & Lt; Endl; If (n> 999) {cout & lt; & Lt; "Invalid value"; Return -1; } // ensuring size of the size of the array; & Lt; & Lt; "Enter" & lt; & Lt; N & lt; & Lt; "Maximum Marks:"; // (i = 0; i & lt; n; i ++) is asking for the array {cin & gt; & Gt; A [i]; } Int srchElement, index; Do {cout & lt; & Lt; Andal & lt; & Lt; "Enter the element to search (exit -1):"; // srchElement is defined cin & gt; & Gt; SrchElement; Break if (srchElement == -1); Index = linear search (A, N, SRH, element, Z); // Calling thscanning function if (index == -1) {cout & lt; & Lt; SrchElement & lt; & Lt; "Not present" & lt; & Lt; Endl; } // scanned and {cout & lt; & Lt; SrchElement & lt; & Lt; "Current" & lt; & Lt; Index & lt; & Lt; Endl; }} While (true); Return 0;
int {int, int z, int n, int srchElement] {for (int z = 0; z & lt; n; z ++) {if (a [z] = = SrchElement) {return z;}} Return -1; } And how do you say it:
index = linear search (A, N, SRKelment, Z);
- You pass a value with the call
z
it is nothing but initial and nothing, in main ()
or In the function. - You pass the argument in the wrong order in the function. You are following: unused
z
value in -
n
(from main ()
) - Uninitialized Searching for
z
( from the main
) - is passing in the element that you see as
n
(Array size) (this would probably be the result of the bound error, for example if there is a search for -1
)
< P> Try it: int linearsearch (int a [], int n, int srchElement) {for (int z = 0; z
And here's how you say it:
index = linear search (A, N, SRKelment);
Comments
Post a Comment