Easy C++ Question

PCMarine

Diamond Member
Oct 13, 2002
3,277
0
0
OK, This is probably a walk in the park for you 1337 C++ programmers, but Im a newbie :). OK, I have to construct a program using fuctions which performs a Binary Search on a 100 element array which contains the first 100 even numbers. Then the program displays how many searches it took to find the number. If the inputed number isn't in the array, then the program will display that the number isn't in the array after X number of tries. I think I have pretty much all of the program finished, except I have no clue how to setup the array w/ the even integers.

Here is my Program so far:

//Binary Search

#include<iostream.h>
#include<iomanip.h>

void input(int &num,int cont);
void binary_search(int a[100], int hi, int lo, int num, int &cont);

int main()
{
int a[100]; //*************** Here is where I need to fix up the array...
int num;
int cont = 1;
int lo = 0;
int hi = 99;

while (cont == 1)
{
input(num, cont);
binary_search(a, 0, 100, num, cont);
}

return (0);
}

void input (int &num,int cont)
{
if (cont == 1)
{
cout << "Enter the number for which you want to search: ";
cin >> num;
cout << endl;
}
}

void binary_search(int a[100], int lo, int hi, int num, int &cont)
{
int mid;
int count = 1;
mid = (lo + hi) / 2;

while((a[mid] != num) && (lo <= hi))
{
count++;
if(a[mid] > num)
{
hi = mid - 1;
}
else
{
lo = mid + 1;
}
mid = (lo + hi) / 2;
}
if(lo <= hi)
{
cout << "A binary search found the number in ";
cout << count << " comparisons.";
cout << endl;
}
else
{
cout << "Number not found by binary search after ";
cout << count << " comparisons.";
cout << endl;
}
cout << "Would you like to Continue with the Program? (1/0)";
cin >> cont;
cout << endl;
}

You can also DL the source code here:

http://thesasclan.com/stuff/Binary_Search_v2.cpp
 

mjquilly

Golden Member
Jun 12, 2000
1,692
0
76
for (int i = 1; i <= 100; i++)
a{i} = i * 2;

replace the "{}"'s w/ "[ ]"'s (damn ubb or whatever it is;))
 

PCMarine

Diamond Member
Oct 13, 2002
3,277
0
0
You = The man!!!

I spent 1-2 hours of frustration trying to think of how to get that to work, and you solved it with a measily 2 lines of code!

Thanks!!
 

ElDonAntonio

Senior member
Aug 4, 2001
967
0
0
Do you really have to do a binary search? or are you free to use other methods for finding the number? because you'd just have to divide by 2 the number you're looking for to get its exact position in the array.
 

EagleKeeper

Discussion Club Moderator<br>Elite Member
Staff member
Oct 30, 2000
42,589
5
0
Originally posted by: ElDonAntonio
Do you really have to do a binary search? or are you free to use other methods for finding the number? because you'd just have to divide by 2 the number you're looking for to get its exact position in the array.

I suspect the intention of the assignment is to develop the understanding for a binary search.

The example chosen was to keep it simple for newbies.