Reputation: 327
So I'm having trouble figuring out how to make this piece of code cout the message after the for loop is done. I keeps doing it after every loop. I have multiple for loops checking if a function is increasing/decreasing/non-decreasing/non-increasing. I'm only going to post the increasing one because they're all having the same problem.
I've tried it this way:
for(i=0; i<n; i++)
{
if(val[i] < val[i+1])
{
cout << "Function is increasing!" << endl;
}
}
And with a counter but I'm pretty sure I used the counter wrong.
Upvotes: 0
Views: 559
Reputation:
Use a simple state machine: check that all points verify your condition. If they do, print something.
bool increasing = true;
for (i=0 ; i<n ; i++)
{
increasing &= val[i] < val[i+1];
}
if (increasing)
{
std::cout << "Function is increasing!\n";
}
Upvotes: 2
Reputation: 475
You could juste create a variable to save the state of the function:
enum State {
Increasing,
Decreasing,
NonDecreasing,
NonIncreasing
} state;
and set it correctly in your loop
for(i=0; i<n; i++)
{
if(val[i] < val[i+1])
{
state = State::Increasing;
}
}
switch(state) {
case Increasing:
std::cerr << "Increasing" << std::endl;
break;
case Decreasing:
...
}
Upvotes: 1