What is wrong with my program? It says I have a syntax error: expected expressio
ID: 3566829 • Letter: W
Question
What is wrong with my program? It says I have a syntax error: expected expression on the two places that I have bolded. This program is supposed to do a binary search in C++
#include <iostream>
#include <cstdlib>
#include <fstream>
const int MAX_NUMBER = 100;
using namespace std;
int input(int a[], int size)
{
if(size <= MAX_NUMBER)
{
ifstream in_file;
in_file.open("Numbers.txt");
if (in_file.fail())
{
cout << "Failed to open file." << endl;
exit(1);
}
int stuff;
int i = 0;
while(in_file >> stuff)
{
a[i] = stuff;
i++;
}
i--;
return i;
}
return 0;
}
int search(const int array[], int key, int size)
{
int lowerbound = 0;
int upperbound = size;
int position = (lowerbound + upperbound) / 2;
while((array[position] != key) && (lowerbound <= upperbound))
{
if (array[position] > key)
{
upperbound = position - 1;
}
else
{
lowerbound = position + 1;
}
position = (lowerbound + upperbound) / 2;
}
if (lowerbound <= upperbound)
{
return position;
}
else
return -1;
}
int main()
{
int a[MAX_NUMBER];
int size;
size = input(a[], size);
int input;
cout << "Please enter a target number that you would like to search for: " << endl;
cin >> input;
int pos = search(a[], input, size);
cout << pos;
return 0;
}
Explanation / Answer
#include <iostream>
#include <cstdlib>
#include <fstream>
const int MAX_NUMBER = 100;
using namespace std;
int input(int a[], int size)
{
if(size <= MAX_NUMBER)
{
ifstream in_file;
in_file.open("Numbers.txt");
if (in_file.fail())
{
cout << "Failed to open file." << endl;
exit(1);
}
int stuff;
int i = 0;
while(in_file >> stuff)
{
a[i] = stuff;
i++;
}
i--;
return i;
}
return 0;
}
int search(const int array[], int key, int size)
{
int lowerbound = 0;
int upperbound = size;
int position = (lowerbound + upperbound) / 2;
while((array[position] != key) && (lowerbound <= upperbound))
{
if (array[position] > key)
{
upperbound = position - 1;
}
else
{
lowerbound = position + 1;
}
position = (lowerbound + upperbound) / 2;
}
if (lowerbound <= upperbound)
{
return position;
}
else
return -1;
}
int main()
{
int a[MAX_NUMBER];
int size; //initialize size
size = input(a, size); //removed a[]
int input;
cout << "Please enter a target number that you would like to search for: " << endl;
cin >> input;
int pos = search(a, input, size);
cout << pos;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.