Using cout inside an FOR loop - c++

I tried testing the following code and found that the loop is never executed :
int i=0;
for(;i++;cout<<i)
{
if(i==5)
break;
}
I read the following post about the value returned by cout from the following post :
What's the difference between cout<<cout and cout<<&cout in c++?
But, I am unable to figure out why. Can someone help me with this.

int i = 0;
for (; i++; cout << i)
At the 1st loop, i++ is evaluated as 0 before increment happens and thus terminates the loop.

The first time the loop exit condition (i++) is checked, i's value is 0 (i.e. false). Hence it never enters the loop.
i++ is post increment. So i becomes 1 but the value which is checked in the loop exit condition is the value before increment - i.e. 0.

Related

The for loop isn't entered even if the initial requirement is true

I have the following function with a for loop inside it. The code is run on an Arduino and the Serial.print function shows that the function is entered correctly with the correct input value. But the for loop isn't entered. Does anyone have an idea why?
void openvalveCold(int steps){
Serial.println(steps);
// Steps is confimed to be 200.
digitalWrite(sleep1,HIGH);
for (antalsteg = 0; antalsteg == steps; antalsteg++)
{
Serial.println("2");
//digitalWrite(dir1,HIGH);
digitalWrite(stepp1,HIGH);
delay(25);
digitalWrite(stepp1,LOW);
delay(25);
Serial.println(antalsteg);
nr_of_steps_cold++;
}
}
void loop{
// calling on function
openvalveCold(200);
}
A for loop is usually constructed like this:
for(init counter; condition; increase counter)
You have made the (false) assumption that it loops until the condition is true. That's wrong. It loops while it is true. Change to:
for (antalsteg = 0; antalsteg < steps; antalsteg++)
The loop isn't entered because the condition is false when the loop starts:
for (antalsteg = 0; antalsteg == steps; antalsteg++)
When the conditional of the loop is first evaluated, antalsteg is 0 and steps is 200. So antalsteg == steps evaluated to 0 == 200 which is false. So the loop is never entered.

Update statement in empty for loop

A similar question has been answered here[https://stackoverflow.com/a/13421435/3276830 ]. The author says
The following code
for (i=0;i<5;i++);
{
printf("hello\n");
}
is interpreted as follows:
Repeat five times for (i=0;i<5;i++)
... do nothing (semicolon)
Open a new scope for local variables {
... Print "hello"
Close the scope }
However, for the following for loop
int i = 0;
for(;i++;cout<<i<<" ");
cout<<i<<" ";
The output I get is just 1, but I expected it to be 123456.....
Edit, I know the difference between prefix and postfix operation. But yeah I did miss that it was 0 the first time loop ran.
int i = 0;
for(;i++;cout<<i<<" ");
This loop can never execute because i is 0, so i++ evaluates to 0 (the value before incrementing it) which is false. Try ++i instead.
the
for(;;i++, cout<<i<<" ");
looks more aesthetically :) correct and will work no matter prefix or postfix

My while loop exits prematurely

thanks for reading this.
I am writing a code to read a big data file. And I try to use a while loop to read it one piece at a time.
But when I write
while(TimeStep++)
it will exit at the first loop.
if I write,
while(TimeStep+=1)
it will be just fine.
Also, if I initialize
int TimeStep=-1;
it will exit at the first loop. But if I initialize
int TimeStep=0;
it will be fine. The magic of while() confuse me. Please help me understand while loop.
Here is all my code.
//get diffusion of all the particles in the 256Coordinate.txt file and diffusion of a single particle.
using namespace std;
typedef vector<double> vec;
int ReadStructure(vec & Coordinate,int size,ifstream & TrajectoryFile){
double a;
for(int i=0;i<size*3;i++){
if(!(TrajectoryFile.eof())){
TrajectoryFile>>a;
Coordinate[i]=a;
}
}
//cout<<Coordinate[1]<<endl;
if(TrajectoryFile.eof()){
return 1;
} else {
return 0;
}
}
int main(){
int ContinueFlag=0,i,j,k;
double a,b,c;
vec Coordinate;
string filename= ("../256Coordinate.txt"); // a file that contains 256*5000*3 numbers
int size=256;
Coordinate.resize(size*3);
int TimeStep=0;
ifstream TrajectoryFile(filename.c_str());//open the .txt file and begin the read data
//TrajectoryFile>>a;
//cout<<a<<endl;
while(TimeStep+=1){//keep looping untils breaks.
ContinueFlag=ReadStructure(Coordinate,size,TrajectoryFile);//read the .txt file and store the values in the vector Coordinate[3*256]. Read 3
*256 numbers at a time.
// cout<<"ContinueFlag= "<<ContinueFlag<<endl;
if(ContinueFlag==1) break;//if we reach the end of the file, exit.
// cout<<Coordinate[1]<<endl;
}
cout<<"total number of timesteps= "<<TimeStep-1<<endl;
}
the body of while loop will execute when the loop condition under
while(loop condition)
is true.
So if you set TimeStep =0 to start with. It will test whether TimeStep ==0 before executing the while loop. Any non-zero value is treated as True. If it is 0, loop body will not execute.
If you initialize as int TimeStep=-1;, TimeStep+=1 will set TimeStep =0, which is equivalent to false, so loop body will not execute.
If you do not know the loop termination condition beforehand, simply use
while (true)
is better than using such a TimeStep variable.
Try:
while(true){
ContinueFlag=ReadStructure(Coordinate,size,TrajectoryFile);
if(ContinueFlag==1)
break;
}
In C++ the integer value 0 is False, any other value including negative integer is True. While loop exits when false.
I think your main problem is not understanding the while loop, it's understanding the increment operator ++.
Let's work with an example:
int x = 5;
int y = x++;
Here, x will have a value of 6 (because you made ++), but which value will y have? Actually, it will be 5. This is a so-called 'postincrement' operator: see, you assign first, and increment later.
If you wrote this
int x = 5;
int y = (x += 1);
Then you would have x = 6 as before, but this time y = 6 also, so you first increment x and only then assign it to y.
This should make your while loop misunderstanding go away:
int TimeStep = 0;
while(TimeStep++)
Here, TimeStep will get the value of 1, but only after it was used by while to test for exit, but while will see the old value (as y in the example above), and the old value is 0, so while exits immediately.
int TimeStep = 0;
while(TimeStep+=1)
In this case the loop goes on because you first increment the TimeStep and then let while test if it's nonzero.
I would really suggest you write a simple loop, why are you testing if TimeStep is nonzero anyway? Just do it like this:
while(true) { // Infinite cycle, until brake is encountered
TimeStep++;
}
The while loop expects a true/false value, according to that, TimeStep++ if TimeStep = -1 is false, because TimeStep++add 1 to TimeStep , so == 0, if TimeStep = 0and you add 1 then is ALWAYS true, because true is every value != 0...
I think you may need to get a better understanding of boolean algebra.
Here's a link to a tutorial http://www.electronics-tutorials.ws/boolean/bool_7.html.
A while loop is based around a boolean expression. If the expression within the while loop parentheses is true it will enter the loop and stop until that expression evaluates to false.
It works when the integer that you are using is set to 0 or 1 because 0 represents false and 1 represents true. You can't use an integer as a boolean expression if it is not 0 or 1.
It looks like you want the loop to break when ContinueFlag==1. So just use that as the while loop parameter. An alternative way would be to just change that code to while (true).
Since you want ContinueFlag to be set at least once (so you know when to break) I would suggest using a do while loop which executes at least once and then repeats if the expression is true.
USE THIS:
do {
ContinueFlag=ReadStructure(Coordinate,size,TrajectoryFile);
TimeStep++; //This allows for TimeStep to increment
} while (ContinueFlag!=1); //It will loop while ContinueFlag!=1 which will cause
//the loop to end when ContinueFlag==1
This is a better way of writing your code (as opposed to while (true)). This allows you to easily see what the purpose of the loop is.

For loop adding to a variable

I am trying to create a loop that adds 1 to a int variable every time the if statement is true
But while testing the code even though the if statement is true the variable is not incremented, as if the my for loop is not incremented at all....
Code sample:
int left_jab_count;
if(area >=100000 && area1 <100000)
{
cout<<"LEFT JAB HAS BEEN THROWN"" "<<area<<endl;
for(int left_jab_count = 0; left_jab_count < 0 ;++left_jab_count)
{
cout<<"Left Jab :"<<left_jab_count<<endl;
}
}
can anybody see where am going wrong here ?
for(int left_jab_count = 0; left_jab_count < 0 ;++left_jab_count)
//^^^^left_jab_count is never < 0
// change <0 to some value larger than 0
you for loop is never executed. Therefore, left_jab_count will never get incremented, you never enter the body of for loop.
Meanwhile, you declared left_jab_count twice.
tacp has adequately covered the issues with your current code, so I won't go into those. Based on your specification, "I am trying to create a loop that adds 1 to a int variable every time the if statement is true", what you want is something like this:
int left_jab_count = 0; // Don't forget to initialise this
while (true) // Replace with real loop
{
// Do NOT initialise left_jab_count here, otherwise it will be
// reset to 0 on every loop
// Insert code which changes area and area1
if (area >= 100000 && area1 < 100000)
{
cout << "LEFT JAB HAS BEEN THROWN " << area << endl;
left_jab_count++;
}
}
Unless you've misstated your specification, then you don't need a for loop inside the if block.
JBentley answered the question which was set by you. In the While statement that he posted you should add a condition which is true so that the code inside can run. I guess you want to enter:
while (left_jab_count < NUMBER)
Be sure to have a true condition so that the loop can start and run the if statement.

Post-increment and pre-increment within a 'for' loop produce same output [duplicate]

This question already has answers here:
Difference between pre-increment and post-increment in a loop?
(22 answers)
Closed 8 years ago.
The following for loops produce identical results even though one uses post increment and the other pre-increment.
Here is the code:
for(i=0; i<5; i++) {
printf("%d", i);
}
for(i=0; i<5; ++i) {
printf("%d", i);
}
I get the same output for both 'for' loops. Am I missing something?
After evaluating i++ or ++i, the new value of i will be the same in both cases. The difference between pre- and post-increment is in the result of evaluating the expression itself.
++i increments i and evaluates to the new value of i.
i++ evaluates to the old value of i, and increments i.
The reason this doesn't matter in a for loop is that the flow of control works roughly like this:
test the condition
if it is false, terminate
if it is true, execute the body
execute the incrementation step
Because (1) and (4) are decoupled, either pre- or post-increment can be used.
Well, this is simple. The above for loops are semantically equivalent to
int i = 0;
while(i < 5) {
printf("%d", i);
i++;
}
and
int i = 0;
while(i < 5) {
printf("%d", i);
++i;
}
Note that the lines i++; and ++i; have the same semantics FROM THE PERSPECTIVE OF THIS BLOCK OF CODE. They both have the same effect on the value of i (increment it by one) and therefore have the same effect on the behavior of these loops.
Note that there would be a difference if the loop was rewritten as
int i = 0;
int j = i;
while(j < 5) {
printf("%d", i);
j = ++i;
}
int i = 0;
int j = i;
while(j < 5) {
printf("%d", i);
j = i++;
}
This is because in first block of code j sees the value of i after the increment (i is incremented first, or pre-incremented, hence the name) and in the second block of code j sees the value of i before the increment.
The result of your code will be the same. The reason is that the two incrementation operations can be seen as two distinct function calls. Both functions cause an incrementation of the variable, and only their return values are different. In this case, the return value is just thrown away, which means that there's no distinguishable difference in the output.
However, under the hood there's a difference: The post-incrementation i++ needs to create a temporary variable to store the original value of i, then performs the incrementation and returns the temporary variable. The pre-incrementation ++i doesn't create a temporary variable. Sure, any decent optimization setting should be able to optimize this away when the object is something simple like an int, but remember that the ++-operators are overloaded in more complicated classes like iterators. Since the two overloaded methods might have different operations (one might want to output "Hey, I'm pre-incremented!" to stdout for example) the compiler can't tell whether the methods are equivalent when the return value isn't used (basically because such a compiler would solve the unsolvable halting problem), it needs to use the more expensive post-incrementation version if you write myiterator++.
Three reasons why you should pre-increment:
You won't have to think about whether the variable/object might have an overloaded post-incrementation method (for example in a template function) and treat it differently (or forget to treat it differently).
Consistent code looks better.
When someone asks you "Why do you pre-increment?" you'll get the chance to teach them about the halting problem and theoretical limits of compiler optimization. :)
This is one of my favorite interview questions. I'll explain the answer first, and then tell you why I like the question.
Solution:
The answer is that both snippets print the numbers from 0 to 4, inclusive. This is because a for() loop is generally equivalent to a while() loop:
for (INITIALIZER; CONDITION; OPERATION) {
do_stuff();
}
Can be written:
INITIALIZER;
while(CONDITION) {
do_stuff();
OPERATION;
}
You can see that the OPERATION is always done at the bottom of the loop. In this form, it should be clear that i++ and ++i will have the same effect: they'll both increment i and ignore the result. The new value of i is not tested until the next iteration begins, at the top of the loop.
Edit: Thanks to Jason for pointing out that this for() to while() equivalence does not hold if the loop contains control statements (such as continue) that would prevent OPERATION from being executed in a while() loop. OPERATION is always executed just before the next iteration of a for() loop.
Why it's a Good Interview Question
First of all, it takes only a minute or two if a candidate tells the the correct answer immediately, so we can move right on to the next question.
But surprisingly (to me), many candidates tell me the loop with the post-increment will print the numbers from 0 to 4, and the pre-increment loop will print 0 to 5, or 1 to 5. They usually explain the difference between pre- and post-incrementing correctly, but they misunderstand the mechanics of the for() loop.
In that case, I ask them to rewrite the loop using while(), and this really gives me a good idea of their thought processes. And that's why I ask the question in the first place: I want to know how they approach a problem, and how they proceed when I cast doubt on the way their world works.
At this point, most candidates realize their error and find the correct answer. But I had one who insisted his original answer was right, then changed the way he translated the for() to the while(). It made for a fascinating interview, but we didn't make an offer!
Hope that helps!
Because in either case the increment is done after the body of the loop and thus doesn't affect any of the calculations of the loop. If the compiler is stupid, it might be slightly less efficient to use post-increment (because normally it needs to keep a copy of the pre value for later use), but I would expect any differences to be optimized away in this case.
It might be handy to think of how the for loop is implemented, essentially translated into a set of assignments, tests, and branch instructions. In pseudo-code the pre-increment would look like:
set i = 0
test: if i >= 5 goto done
call printf,"%d",i
set i = i + 1
goto test
done: nop
Post-increment would have at least another step, but it would be trivial to optimize away
set i = 0
test: if i >= 5 goto done
call printf,"%d",i
set j = i // store value of i for later increment
set i = j + 1 // oops, we're incrementing right-away
goto test
done: nop
If you wrote it like this then it would matter :
for(i=0; i<5; i=j++) {
printf("%d",i);
}
Would iterate once more than if written like this :
for(i=0; i<5; i=++j) {
printf("%d",i);
}
Both i++ and ++i is executed after printf("%d", i) is executed at each time, so there's no difference.
You could read Google answer for it here:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Preincrement_and_Predecrement
So, main point is, what no difference for simple object, but for iterators and other template objects you should use preincrement.
EDITED:
There are no difference because you use simple type, so no side effects, and post- or preincrements executed after loop body, so no impact on value in loop body.
You could check it with such a loop:
for (int i = 0; i < 5; cout << "we still not incremented here: " << i << endl, i++)
{
cout << "inside loop body: " << i << endl;
}
The third statement in the for construct is only executed, but its evaluated value is discarded and not taken care of.
When the evaluated value is discarded, pre and post increment are equal.
They only differ if their value is taken.
Yes, you'll get exactly same outputs for both. why do you think they should give you different outputs?
Post-increment or pre-increment matters in situations like this:
int j = ++i;
int k = i++;
f(i++);
g(++i);
where you provide some value, either by assigning or by passing an argument. You do neither in your for loops. It gets incremented only. Post- and pre- don't make sense there!
There is a difference if:
int main()
{
for(int i(0); i<2; printf("i = post increment in loop %d\n", i++))
{
cout << "inside post incement = " << i << endl;
}
for(int i(0); i<2; printf("i = pre increment in loop %d\n",++i))
{
cout << "inside pre incement = " << i << endl;
}
return 0;
}
The result:
inside post incement = 0
i = post increment in loop 0
inside post incement = 1
i = post increment in loop 1
The second for loop:
inside pre incement = 0
i = pre increment in loop 1
inside pre incement = 1
i = pre increment in loop 2
Compilers translate
for (a; b; c)
{
...
}
to
a;
while(b)
{
...
end:
c;
}
So in your case (post/pre- increment) it doesn't matter.
EDIT: continues are simply replaced by goto end;