-
Search an array
Hello everyone, I've trying to perfect this code and spruce it up a little bit , constantly adding things to see how much I can make it do. Unfortunaltely, I am still having a little problem with my peeking function. I have added a user input so that someone can enter a value but when I attempt to have the program search for that particular value, it seems to not work correctly. It only looks at the first value within the array and not the entire array. For example if the value is 5 that the user is searching for, and the users entries are 5,4,3,2...we will get a (true/1) positive return....
if the values entered are 1,2,3,5..even though 5 is there we will get a negative return.
I am also getting a warning message
warning C4715: 'Stack::peek' : not all control paths return a value
Please help
oh and Thank you to
everyone who has helped me so far
Code:
#include <iostream.h> //This is my preprocessor directive for the cout/cin statements//
const int Stack_Size=100; //Initialization of Stack Size//
class Stack
{
public:
Stack(); //constructor//
void push(int);
int pop();
bool peek();
bool empty();
bool full();
private:
int count;
int data[Stack_Size];
};
Stack::Stack()
{
count=-1;
}
void Stack::push(int value)
{
count++;
data[count]=value;
}
int Stack::pop()
{
int topvalue;
topvalue=data[count];
count--;
return(topvalue);
}
bool Stack::peek()
{
int i=0;
int value;
cout<<" Please enter the value you are searching for? ";
cin>>value;
for (i=0; i<count; i++)
{
if (data[i]==value)
return 1;
else
return 0;
}
}
bool Stack::empty()
{
if (count==-1)
return 1;
else
return 0;
}
bool Stack::full()
{
if (count==Stack_Size-1)
return 1;
else
return 0;
}
int main()
{
Stack entries;
int number;
char answer;
cout<<" Please enter as many digits as you wish.\n If you wish to end your entries, please enter a number greater than 10\n ";
while(1)
{
cout<<"Digit:\n";
cin>>number;
if (number>9) //If the entry is >9, the loop will break and that number will not count in the stack//
break;
if (entries.full()) //If there are more than 10 entries, the loop will break and give a message//
{
cout<<"The stack is full and you do not have any space left\n";
break;
}
else
entries.push(number);
}
if (entries.peek())
{
cout<<"This stack does contain your value \n";
}
else
cout<<" This stack does not contain your value \n";
if (entries.empty()) //If there are no valid (anything <=9 is valid) entries, message below will be printed out//
{
cout<<"The stack is empty\n";
}
else
while (!entries.empty())
{
cout<<" Do you want to pop an item from the stack? ";
cin>>answer;
if (answer=='y')
cout<<entries.pop()<<endl;
else
break;
}
return 0;
}
-
> warning C4715: 'Stack::peek' : not all control paths return a value
It doesn't return a value if the for loop completes.
Remember, a for loop can execute zero times, so this function could just fall off the end.