I was not really clear with the post increment operator that I always used with for loops.
My latest and newly acquired understanding of post increment operator is the following:
int a = 5
int b = a++ //a will increment and return back its old value 5
so b = 5
Armed with this new knowledge i decided to understand/apply it to the places where i commonly used the post increment operator as in a for loop . Now it seems like I am lost
since I am ending up with the wrong output theoretically
Consider the following code
for(int i=0 ; i< 3 ; i++)
{
std::cout << i;
}
First loop
i starts with 0 which is less than 3 so ( increment by 1 however since its i++ it returns old value 0)
so cout should display 1 // But it displays 0
Second Loop
i is now 1 which is less than 3 so i++ is applied - Now i is 2 and returns back 1
so cout should display 2 //But it display 1
Third Loop
i is now 2 which is less than 3 so i++ is applied - Now i is 3 and returns back 2
so cout should display 3 //But it display 2
Fourth Loop
i is now 3 which is not less than 3 so loop exits
Could anyone please clear my understanding and point me in the right direction.
The output should be 0,1,2 where am i going wrong ?
What you're missing is when each of those sections of the for statement happen:
for (int i = 0 ; i < 3 ; i++)
// 111111111 22222 333
The first bit happens once before any iterations are done.
The second expression is evaluated before each potential iteration and, if false, no further iterations are done.
The third bit is done at the end of each iteration, before returning to evaluate the second bit.
Now re-read that last bullet point carefully. The i++ is done at the end of an iteration, after the cout << i. And, immediately after that, the continuation condition is checked (the second part).
So the loop is effectively the same as:
{ // Outer braces just to limit scope of i, same as for loop.
int i = 0;
while (i < 3) {
cout << i;
i++;
}
}
That's why you get 0 1 2.
The semicolons in a for loop delimit three different expressions. The value of the third expression is irrelevant to the behavior of the loop. You could replace i++ with ++i and your loop would behave the same; either way, i is incremented by 1.
To observe the behavior of the increment operators, consider the following loops:
for(int i = 0 ; i++ < 3 ; ) cout << i;
/* ^^^ Nothing here! */
Note that the third expression is empty. The output is 123—0 is skipped because the test, including increment, occurs before every iteration of the loop.
How does the postincremented loop behave compared to a similar one with the preincrement operator?
for(int i = 0 ; ++i < 3 ; ) cout << i;
Now the output is 12—3 is not printed because the conditional test sees the value 3 as soon as it is incremented to that, so the loop exits.
You just need to know that the statement int i = 0 is executed first , i.e , i takes first the value 0 , checks if the condition is true and then what the loop body is executed .
Then , i is incremented.
Related
I am extremely new to the coding world. I just have a basic question regarding this function that squares integers from 0-9. I understand most of what's going on until I get to
std::cout << i << " " << square << "\n";
i = i + 1;
I'm not too sure how that ends up causing the output to square the results in order from 0-9. Can someone explain the reasoning behind this line of code? Here is the code for this function.
#include <iostream>
int main() {
int i = 0;
int square = 0;
while ( i <= 9) {
square = i*i;
std::cout << i << " " << square << "\n";
i = i + 1;
}
return 0;
}
This code:
std::cout << i << " " << square << "\n";
i = i + 1;
Doesn't square anything. It is merely outputting the current square that has already been calculated, and then increments i for the next loop iteration.
The actual squaring happens here:
square = i*i;
So, the code starts at i=0, calculates square=0*0 and displays it, then sets i=1, calculates square=1*1 and displays it, then sets i=2, calculates square=2*2 and displays it, and so on until i exceeds 9, then the loop stops.
Lets start from beginning and what is happening, I will ignore first several lines and start at:
int i = 0;
int square = 0;
You see when you say int i; your compiler says I need to allocate bucket of memory to hold value for i. When you say i = 0 zero is put into that memory bucket. That is what is happening for square as well.
Now to loop
while ( i <= 9 ) {
square = i*i;
std::cout << i << " " << square << "\n";
i = i + 1;
}
So, lets ignore
square = i*i;
std::cout << i << " " << square << "\n";
for now we will come to it later.
So
while ( i <= 9 ) {
i = i + 1;
}
goes into the loop and gets value from i's bucket, adds 1 and puts new value into the i's bucket. So in first loop it will be i = 0 + 1, put 1 into i bucket. Second, i = 1 + 1 put 2 in, third i = 2 + 1 put 3.
So lets go back to square and its bucket.
square = i*i;
So first time we go into the loop i = 0 and square = 0 * 0 so compiler puts 0 into square's memory bucket. Next time it hits square i has been incremented to 1 so square = 1 * 1, thus compiler puts 1 into the bucket. Third time i is 2 so square = 2 * 2, and compiler puts 4 into the bucket. And so on till it i <= 9. When i hits 10 loop is not executed.
In comments you have stated that you do not know the difference between a math equation and an assignment statement. You are not alone.
I will try to explain, as an addition to existing answers, to provide a different angle.
First, two examples of math equations:
x = 1 +1
y+1 = x*2
To illustrate their meaning, let me point our that you first can determine that x is 2 and in a second step that y is 3.
Now examples of assignment statements.
x = 1 +1;
y = x*2;
The minor difference is the ; at the end, tipping you off that it is a program code line.
Here the first one looks pretty much the same as the first equation example. But for a C compiler this is different. It is a command, requesting that the program, when executing this line, assigns the value 2 to the variable x.
The second assingment statement I made similar to the second equation example, but importantly different, because the left side of = is not an expression, not something to calculate. The equation-turned-statement
y +1 = x*2;
does not work, the compiler will complain that it cannot assign a value (no problem with doing a little calculation on the right side) to an expression. It cannot assign the value 4 to the expression y+1.
This helps with your problem, because you need to understand that both lines
i = i + 1;
square = i*i;
are statements which, when executed (and only then) cause a change to the value of the variable in that line.
Your program starts off with the value 0 in the variable i. At some point it executes the first of the statements above, causing the value of i to change from 0 to 1. Later, when the same line is executed again, the value of i changes from 1 to 2. So the values of i change, loop iteration by loop iteration, to 2,3,4,5,6,7,8,9
The second assignment line causes the value of square to become the value of i, whatever it is during that loop iteration and multiplied by itself. I.e. it gets to be 4,9,16,25,36....
Outputting the value of square each time in the loop gets you the squares.
Since you state that you basically understand loops, I just mention that the loop ends when i is not lower or equal to 9 any more.
Now from the other point of view.
If you try to solve the equation
i = i + 1
for i, you should hear your math teacher groaning.
You can subtract i from both sides and get
0 = 1
The solution is "Don't try.", it is not an equation.
std::cout << i << " " << square << "\n"; prints every
number i next to its square, which is previously computed
(square = i*i;).
i = i + 1; increments i to compute the next square. It stops when i reaches 10.
The output will look like this:
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
So we have a while loop here, which run while i <= 9. The square of any number i is i * i.
while(i <=9){ //check the condition and then enter the body
//body
}
But we need a condition to get out of the loop, otherwise our program will enter into an infinite loop.
To ensure, we will exit from the loop we increase the value of i by 1.
so at first when i = 0 square = 0 * 0 = 0,now we increase the value of i i.e now i becomes one which still satisfies the condition to stay inside the loop , again it will calculate square = 1 * 1 until and unless the value of i remains less than or equal to 9.
Once the condition fails, the execution comes out of the loop.
I am new to C++ and I am trying to achieve a backward for loop, I founded solutions which works very well but I want to know what my version is not correct and making an infinite loop.
Here is a working version that I founded (I don't understand how we can decrease i in the condition..) :
for (unsigned i = size ; i-- > 0 ; )
{
// do stuff with i
}
Here is a version I wrote which works but don't go down to 0 (this way seems more logical to me) :
for (unsigned i = size-1 ; i > 0 ; i--)
{
// do stuff with i
}
If I say for exemple n=10, I will get this if I print i in the loop :
9
8
7
6
5
4
3
2
1
And here is the version which for me is the more logical and should go down to zero but is providing an infinite loop.
for (unsigned i = size-1 ; i >= 0 ; i--)
{
// do stuff with i
}
Could someone explain to me why the last version isn't working and what is the best choice to make ?
An unsigned number is always >= 0. (When it reaches zero a further decrement sets it to std::numeric_limits<unsigned>::max())
So your final for loop is equivalent to
for (unsigned i = size-1 ; true ; i--)
which, of course, loops forever.
In your first loop, you have i-- > 0 as the stopping condition. When i is zero, i-- is an expression with value zero (so the loop halts), despite the fact that i is then set to std::numeric_limits<unsigned>::max(). Some folk like (me included; cue the downvotes) to write i-->0 and regard --> as the slide operator. See What is the "-->" operator in C++?
The statement i >= 0 is always true because i is unsigned which means that is never below zero. If you decrease the value while i is zero, there will occur a so-called underflow and it will have a very high number.
The first version certainly gets the job done, so I would stick to it.
for (short i = 1; i < 5; i++)
for (j = 0; j > 0; j--)
cout << i << "\t";
Anybody please answer the above code.. i am getting continuous zero why is it so please explain
First off, you need to declare the variable j somewhere. Assuming you have declared j somewhere else in the program, this program as you have written it here will actually print nothing out.
Since j is set to start at 0, and 0 is not greater than 0, the
cout<<i<<"\t";
line will never actually be run. If you could provide more of your code we may be able to answer your question better. You could try setting j to start at 1 if you want it to actually print out i.
Link to Online IDE running the program
On executing the program, there is no output.
for(short i=1;i<5;i++)
This statement declares and initializes the variable i to 1, checks if it is less than 5 and then moves on to the next statement
for(j=0;j>0;j--)
This statement initializes j to 0 (Note that j has to be declared previously), and then checks if j is greater than 0. As j isn't greater than 0, it doesn't move on to the next statement, i.e. cout<<i<<"\t"; and continues the previous loop, the loop with the variable i.
The i- loop runs 4 times, and since anything isn't actually printed to the screen, you don't get any output.
First this code won't compile as you have not defined j. After you do that, it wont print anything as j is never greater than 0.
#include <iostream>
int main()
{
for(short i=1;i<5;i++)
for(short j=0;j>0;j--)
std::cout<<i<<"\t";
return 0;
}
for (j = 0; j > 0; j--)
This is a zero iteration loop. Initializes j to 0 checks if j is greater than 0.
1) If j=0, the loop undergoes 0 iterations and hence no output.
2) If j=5, you get each of the numbers from 1 to 5 printed 5 times as output.
1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5
Sorry for a probably stupid question.
My loop does not stop at 0 and I have no idea why.
This loop will stop at i = 1
for (unsigned int i = 3 ; i > 0 ; i--)
Whereas this will stop at i = 4294967295 instead
for (unsigned int i = 3 ; i >= 0 ; i--)
Why? Do I miss anything?
In fact this i >= 0 for unsigned int is always true. So you cannot use it as loop invariant.
Use this instead:
for (unsigned int i = 4 ; i-- > 0 ;)
println(i);
it will print 3,2,1,0
A for loop iterates until the break condition evaluates to false.
In your case the loop will repeatedly check:
is i>0 (i>=0 respectively) true? If so, execute body and decrement i, else skip the loop-body.
Your first loop will at some point reach i=1. i>0 will evaluate to true. The body will be executed, i will be decremented. i will then be 0. Hence i>0 will evaluate to false and the body will not be executed and you will break out of the loop.
Your second loop will not stop (tested with g++). Why? Your i will reach 0. i>=0 will evaluate to true. The body will be executed, i will be decremented. But since you are using an unsigned int this will then assign 4294967295 to i. Since 4294967295>=0, the loop will continue, reach 0 again and again assign 4294967295 to i thus executing indefinitely.
This happens since an unsigned int represents 0 as all 0s in binary and subtracting 1 from it will yield all 1s which is interpreted as 4294967295.
How to avoid the problem? As mentioned in the comments a simple way out of it would be to use an int instead of an unsigned int.
char i;
for (i = 1; i < 10, i++;)
{
cout << (i+1) << endl;
}
return 0;
I understand that for loop has the following syntax:
for(initialization; condition; increment)
{
}
As I run the debug, why it never checks the condition and it eventually stops at i = 0?
(Thank you Damien and Andars, I don't know why the "on purpose" statement was removed, but you interpret my question correctly. Could someone explain why the complier skips the condition before the comma, and why the loop stop at i = 0 instead of looping forever? Thanks!)
I believe he is indicating that he wrote the code that way on purpose.
To answer, i++ will always return true. The last value is the value that matters with comma separated statements, so the loop will not stop.
Edit for elaborations:
It isn't simply using a logical or, it disregards what is before the comma and only takes the last value. The value of anything non-zero is considered true, and since i starts at 1, and goes up, it will always be non-zero (until it overflows and wraps back around, which explains why i ends at 0).
If you say:
x = 4, 5, 6;
x will be equal to 6, the last value.
Change
for (i = 1; i < 10, i++;)
to
for (i = 1; i < 10; i++)
Change to
for (i = 1; i < 10; i++) //Notice correct placement of ;
It seems to me also that the code was written incorrectly on purpose. As others have mentioned, the comma operator will discard the value of the i<10 and only i++ will be evaluated as condition. This will return true until i overflows (values only from -127 to 127) and ends up at -1, when i++ will return 0 and the loop exits. Thus the final value for i will be 0.
Because you used the comma operator instead of a semi-colon