I wrote a simple code to search an element in an array that can be input by the user. However, the array does not take more than 6 values.
Here is the code. (It still isnt complete)
#include<iostream>
usingnamespace std;
void search( int item[], int size, int object);
int main()
{
int i, elements[i], size, obj;
cout<<"Enter the number of elements: ";
cin>>size;
cout<<endl;
for(i=0; i<=size; i++)
{
cin>>elements[i];
}
for(i=0; i<=size; i++)
{
cout<<elements[i]<<" ";
}
cout<<endl;
cout<<"Enter the element to search: ";
cin>>obj;
search( elements, size, obj);
return 0;
}
void search(int item[], int size, int object)
{
int k, key;
for(k=0; k<size; k++)
{
key= item[k];
if(key== object)
{
cout<<"The element is in "<<k+1<<" place.";
break;
}
//else if(
}
}
i is not initialised, so it can contain any garbage value.
The number of items in the array elements must be a constant, known at compile time. You tried to use a variable, which is not valid in C++, and of course it is also invalid since the variable was not initialised.
It should look something like this:
1 2
constint size = 100; // set required number of elements in array.
int elements[size]; // array dimension is a constant known at compile time.
If you want a variable sized array, decided at runtime, use a vector (or dynamically allocate using new []).
So, there is no other way than vector by which I can create an array whose length is decided at runtime?
It's non-standard but I believe the gnu C++ compiler will let you define an array whose size is an expression. Actually if your code compiled then you're using a compiler with this extension. All you would need to do is move the definition of elements and give it the right size:
1 2 3 4 5
int i, size, obj;
cout<<"Enter the number of elements: ";
cin>>size;
cout<<endl;
int elements[size];