-
Don't know what to do
Hi
I am learning how to write "if " code.
what happen if i want set up a range inbetween two numbers?
Such as age between 50 to 100.
Can I write as:
if (age<50)
{
cout<<"good";
}
if (100>age>=50)
{
cout<<"umm....";
}
else
{
cout<<"hello world";
}
thanx
-
you can't use statements like 1>x>0 in an if statement. it would have to be 1 > x && x > 0. also, don't use two if statements. just use an if-else if-else statement:
Code:
if (age < 50)
{
cout<<"good";
}
else if (100 > age && age >= 50) //Changed
{
cout<<"umm....";
}
else
{
cout<<"hello world";
}
-
hmm
yours is absolutely right, but the convention is :
if (age >=50 && age < 100)
-
Anyway, if after the 'if' statement.. only 1 line is followed: eg:
Code:
if (a == b)
{
something;
}
You can also write that as:
Code:
if (a == b)
something;
Or:
Code:
if (a == b) something;
Remember, that if you have more that 1 line to execute after the if statement, you have to include the braces '{}'.
That's it :)
-
Though, its probably a good idea to always use braces anyway. Makes it easier to follow the code, and also if u need to add something in :)
-
Unless you use something like Visual C++ that automatically aligns your code, use braces less. Because then you get back to the program and find lots of if statemets, all nested together and dont know which one's which. Also use the case statement instead of lots of ifs' and else ifs' :)
Good luck :)
-
I tend to agree with fry on the use of braces, particularly at the beginning stages of programming in this language. You'll rarely, if ever, see them used in more sophisticated code where only one line of code follows an IF statement, but new students of C/C++ tend to make enough boo-boos without adding one more pitfall to the mix.
(Addendum: WHILE statements followed by a single line of code don't require braces either, but...)
I couldn't agree more with Ruski's advice of using switch (case) statements in lieu of multiple IF...ELSE's. Much cleaner and more elegant, in my opinion. There's no effective difference in the two methodologies, but a novice looking to write more sophisticated code will likely opt for the switch statement. :)
-Skipper
-
Braces are great, I've only just started using if statements without them. Use them until you are comfortable with C++ and can read code fairly easily because until then layout is veryimportant!
-
Braces are good for starting C++ programming but in a while you'll be using neat and tidy code without them :)