[QUOTE=mlabcdzs;977292]
Code:
#include <iostream>
using namespace std;
int main()
{
for(int x = 0; x < 10; x++)
cout << x <<endl;
cin.get();
return 0;
}
BTW, I am using the tutorial Cprogramming.com Tutorial: Loops
I understand how for loops work. (mostly) I know this prints x while x<10(in this case). Which I have tested and worked fine.
As I was writing this I answered my own question I believe, just want to make sure.
For example this is what I see:
Code:
for(int x = 0; x < 10; x++)
Is this the same as?
Code:
int x = 0;
for( x <10; x++)
[\QUOTE]
Yep, you are right. Except you forgot to put the semicolon before x<10 like so:
The reason I ask this, originally in the first example my mind tells me that it will set x = 0 everytime it gets evaluated. But as I was writing this I realized x is just a variable that is assigned (0) so the compiler skips this part of the for statement correct?
I know there are better ways to write this piece of code I am just trying to grasp everything in the tutorial and practice it.
you are partly right.
when you declare the statement
The compiler initialises i to 0. After that, the compiler would skip the assignment part and only execute the 2nd and first statement. The conditional part, and the incremental part.
so that is why in some compiler if you do this.
Code:
int i =0 ;
//or
int i ;
i =0 ;
// in for loop
for(i=0;i<10;i++){}
Some compilers will give you a warning that you have initialized a variable twice or the value of one will not be used..something like that anyways. Can't remember.
Although you can use a for loop. I find a while loop so much easier and cleaner.
I dunno, it depends.
this cool no? :
Code:
#include <iostream>
using namespace std ;
void main()
{
int i=0;
while(i++<10)
{
cout << i <<endl ;
}
cout << endl ;
system("pause") ;
}
just preference i guess . Don't worry about it.
Loops will be an automatic process before you know it.