difference between for and while loops



whats is the output that statement

for( x=1;x<=10;x=+1)

cout<<x<<endl;

i know the outpout will b 12345678910

but for this statement i did not get it

x=8
while(x<10)
x=x+1
cout<<x;

dont know what would be the output

910

Btw your syntax is wrong. If you want to increment a variable by one, just call the increment operator:

X++

=+ is not valid syntax. Is it actually +=.
yeah this one is just error in typing but the second statement i am trying to figure out what would be the output
If you use braces for 'while' the output will be
910

otherwise if you use above code,the output will be
10
closed account (owbkoG1T)
1
2
3
for( x=1;x<=10;x=+1)

cout<<x<<endl;


1 (on a new line because of endl) infinitely, x = +1 mean "x equals positive one", therefore x will never be anything but 1.

1
2
3
4
x=8
while(x<10)
x=x+1
cout<<x;


10, the cout statement is not a part of the loop (no curly braces).
If you use braces for 'while' the output will be
910

how did u get to that....sorry its my first class in c++
1
2
3
4
5
6
7
int x = 8; // Declare x as an integer and set it to 8

while (x < 10)  // While x is less than 10 ..
{
	x = x+1; //Add one to x
	cout << x; //And then print x
}


It will loop over the stuff inside the { }, each time checking to see if x < 10 is still true. Once x is 10, it isn't anymore, and it'll move past it. So the first time, it'll add one, then print x. "9". 9 is less than 10, so it'll do it again. Add one, and print it. "10". 10 is not less than 10 so it doesn't do it again. Final output is "910"
Last edited on
1
2
3
4
5
6
int x=8;
while(x<10)
{
x=x+1//line 1
cout<<x;//Line 2
}


Above one using braces.
Because 'while' or 'if-else' or 'switch' or 'for' control structures execute only one line of code below to them ,if you dont use braces.
in your code the while(x<10) execute for only x=x+1;
cout<<x; is not part of while loop
ok i got you but how about the first one with for for( x=1;x<=10;x=+1)

cout<<x<<endl;

the cout is a part of the loop
The normal idiom for doing something 10 times is:


1
2
3
4
for( int x=0;x<10;x++) {
    cout << x+1 << endl;
    //do your stuff here
}


As a while loop:

1
2
3
4
5
int x=0;
while (x<10) {
    cout << x+1 << endl;
    x++;
}


And that while can be shortened like this:

1
2
3
4
int x=0;
while (x<10) {
    cout << ++x << endl;
}
Last edited on

but in case i have curly braces for the while statemnt why 10 as an answer as long as 10<10 is not impossible
Your reply doesn't make sense, It's OK maybe English is not your first language, so my reply is this:

Did you try running the code for my last example of the while loop?
Topic archived. No new replies allowed.