Bsearch Linear Search User Defined function.

Can anyone rectify the following code by me. I wanted to do Linear Search through User Defined Functions, The code should tell whether the an Item (inputted by user) is present in the list(inputted by user) or not. Please note that I'm a total beginner.... Please help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  #include<iostream.h>
#include<conio.h>
int f,item;
int bsearch(int [],int,int);
void main()
{
	int x;
	bsearch(x,10,f);
	if(f>0)
	{
		cout<<"\nThe Item is Present in the List";
	}
	else
	{
		cout<<"\nItem not Present in the List";
	}
	getch();
}
int bsearch(int a[],n,f)
{
	clrscr();
	cout<<"\nEnter Number of Elements: ";
	cin>>n;
	cout<<"\n\nEnter Series: ";
	for(i=0;i<n;i++)
	{
		cin>>a[i];
	}
	cout<<"\nEnter Value to be Searched: ";
	cin>>f;
	for(i=0;i<n;i++)
	{
		if(a[i]==item)
		{
			f++;break;
		}
	return(a,n,f);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <conio.h>

bool bsearch();

void main()
{
	if(bsearch())
	{
		std::cout << "\nThe Item is Present in the List";
	}
	else
	{
		std::cout << "\nItem not Present in the List";
	}
	getch();
}

bool bsearch()
{
	clrscr();
	std::cout<< "\nEnter Number of Elements: ";
	std::cin >> n;
        
        int *a = new int[n];
	std::cout << "\n\nEnter Series: ";

	for(int i = 0; i < n; i++)
	{
		std::cin >> a[i];
	}

	std::cout<< "\nEnter Value to be Searched: ";
	std::cin >> f;
	for(int i = 0; i < n; i++)
	{
		if(a[i] == f)
		{
			return true;
		}
	}
        
        return false;
}


- Avoid using global variables
- Doing this :return(a,n,f);, will return just the first element
- If you want to get a function to modify a value for you, you must pass that value by reference or in this case simply make the function return the answer
- Since you don't know the size of the array before-hand, make sure to dynamically allocate space for the array when you know it's size by using new
- Spaces do not make your program slow, use more spaces to show clarity
- Last and certainly not least, you have to be plan your code before you write it, that will give you chance to spot bugs while you are writing
Last edited on
Topic archived. No new replies allowed.