I've tried to perform a simple binary/linear search but there's a problem with the output, I suspect the function isn't being called
A small portion of void main:
void main()
{ cout<<"Linear or Binary? (1/2)"<<endl;
cin>>ch;
switch(ch)
{
case '1': pos = linear();
cout<<"Position: "<<pos;
break;
case '2': pos = binary();
cout<<"Position: "<<pos;
break;
default: cout<<"error"<<endl;
}
}
//here is a function:
int linear()
{
int a, n, ar[n], posn;
cout<<"Enter size of array and array"<<endl;
cin>>n;
for(int i =0; i<n; i++)
{
cin>>ar[i];
}
cout<<"enter element to be found"<<endl;
cin>>a;
for(int j=0; j<n; j++)
{
if(ar[j]==a)
{
posn= j+1;
}
}
return posn;
}
The output is just garbage or junk. None of my couts are showing up, simply one random int junk value.
There are quite a few problems in your code:-
Leaving the values of important varibles such as posn
and n
uninitialized...
C++ invokes undefined behavior the time you try to access the value of a variable that is not initialized... And UB can be anything, so the garbage value is expected ...
To prevent that from happening, initialize them before use...
int a, n, posn = -1; cout<<"Enter size of array and array"<<endl; cin>>n;
C++ does not have the feature of variable length arrays yet (Only in C99 and above...) and hence ar[n]
is not possible (Though there are some compilers like Ideone which support it, but according to the standard, it is not possible), that is why we have got the advantages of a class called vector
inside of the namespace std
Note:
#include <vector>
before use...
int linear() { int a, n, posn = -1; cout << "Enter size of array and array: " << endl; cin >> n; // Use vectors for dynamic arrays (or pointers if you want to stay old-school...) vector ar(n); for(auto i = 0; i < n; i++) cin>>ar[i]; cout << "Enter element to be found: " << endl; cin >> a; for(auto j = 0; j < n; j++) if(ar[j] == a) posn= j + 1; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.