The goal is to search the array and find a specific number in it and return the position. I have the method for how to do it down but trying to get it to run in the main method is giving me the error in the title. What do i do to fix?
#include "stdafx.h"
#include <iostream>
using namespace std;
int searchArray(int a[], int x) {
for (int i = 0; i < a[100]; i++) {
if (x == a[i])
return i + 1;
break;
}
return -1;
}
int main()
{
int wait, x, y, a[100];
//problem 3
cout << "Enter the size of the array(1-100): ";
cin >> y;
for (int i = 0; i < y; i++) {
cout << "Enter an array of numbers:";
cin >> a[i];
}
searchArray(a[100], x); //i get error on this line with a[100]
cin >> wait;
return 0;
}
Expected is it should run with no errors and find position of a number in the array but I just get the error and cant run it.
After the for() loop in main(), you need something like:
cout << "Enter the value to search for: ";
cin >> x;
wait = searchArray(a, x);
cout << x;
cout << " is at position: ";
cout << wait;
int searchArray(int a[], int x)
{
for (int i = 0; i < 100; i++) //change a[100] to 100 because it only needs the size not the array itself
{
if (x == a[i])
return i + 1;
break;
}
return -1;
}
int main()
{
int wait, x, y, a[100];
cout << "Enter the size of the array(1-100): ";
cin >> y;
for (int i = 0; i < y; i++) {
cout << "Enter an array of numbers:";
cin >> a[i];
}
cout<<"Number to look for: "; //sets a value for x
cin>>x;
cout<<"Index: "<<searchArray(a, x)<<endl; //function returns an int therefore a cout is needed
cin >> wait;
return 0;
}
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.