need clarification plz


x=8
if(x==8)
cout<<"welcome";
else
cout<<"go back";
cout<<"home";

the output for this code is welcomehome but i am wondering why is not just welcome
If you don't include any braces if/else statements only effect the statement directly below them. If you wanted it to just print welcome you would have to do.

1
2
3
4
5
6
7
8
9
10
x=8
if(x==8)
{
    cout<<"welcome";
}
else
{
    cout<<"go back";
    cout<<"home";
}
ok but why home and not go back... sorry first time taking c++ and kinda confused with those braces
Because if you do this

1
2
3
4
5
6
x=8
if(x==8)
cout<<"welcome";
else
cout<<"go back";
cout<<"home";


it's the same as

1
2
3
4
5
6
7
8
x=8
if(x==8){
	cout<<"welcome";
} else {
	cout<<"go back";
}
cout<<"home";


In this case the x==8 returns true because x is 8
and it will do
cout << "welcome";
then the if are finish and it moves on to another statement which is
cout << "home";

so it will output "welcome home"

I am newbie here correct me if I am wrong

yes i got youu...

ok here is another one

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

what would be the output
The loop loops as long as x is smaller than 10. Each loop 1 is added to x. So, when x is 9, the computer checks: "Is x smaller than 10?" yes, it is, so the x = x + 1; statement runs once again, and x is made 10. At the next iteration, the expression x < 10 returns false because x is not longer smaller than 10, and so the program continues directly after the while loop, and that is at cout << x; Conclusion: the output will be 10.
Last edited on
yes but why the output is 10 and not 9, u said the expression x<10 returns false because x is not longer smaller than 10

here my understanding

8+1=9
9+1=10 then 10<10 is false
The check happens at the start of the loop.

x is 8.
Check to see if x is less than 10.
It is, because 8 is less than 10, so carry on.
Add one to x (so x is now 9).
Loop is finished. Go back to the check.

x is 9.
Check to see if x is less than 10.
It is, because 9 is less than 10, so carry on.
Add one to x (so x is now 10).
Loop is finished. Go back to the check.

Check to see if x is less than 10.
It is NOT, because 10 is not less than 10. So no more looping.

Output x (which is 10)
Last edited on
I got the concept of that but the output should be the numbers that hey true in the loop ...

for instance

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

the output are 12345678910 ...those that they r true in the loop..


CONFUSEDDDDDDDDDDDDDDDDDDDDD
yeah it starts at one and its less than 10 so it prints it and then ... it gets to 10 and 10 is equal to 10 so it prints it
Topic archived. No new replies allowed.