if (expression) parens required. No "then".
stmt the "body" of the if.
If more than 1 statement
in body enclose in { }
semantics: "meaning"/behaviour:
use:
execute a set of code (the body) if some condition is
met (is true). Don't execute the set of code if the condition
is false.
The expression is a condition of some sort. A question that is true or false.
Relational operators in C: < > <= >= == //equality Single = is assignment operator. Don't confuse them! != //not equalsAn expression with a relational operator evaluates to true or false:
a < b this expression's value is true or false.Every expression will have a single value of a particular type when evaluated.
if (gpa > 3.5)
cout << "Dean's list";
-------------------
if (y != 0) //divide by y only if not zero
x = 1 / y;
-------------------
if (y != 0) { //compound statement
x = 1 / y; //indent the statements of the body
cout << "Reciprocal is: " << x;
}
No semicolon after }
if (expression)
stmt
else //if the expression is not true,
execute the statements of the else part.
stmt // in an if else, either the if body or
// the else body will be executed, one
//or the other but not both
Example program with bad_ifs.cpp
//minimum of two numbers
if (x < y)
min = x;
else
min = y; //what if x equals y?
-------------------------------
if (y != 0) {
x = 1 / y;
cout << "Reciprocal is: " << x;
}
else
cout << "No division by zero";
-------------------------------------------------------------
// counting asterisks and all other chars
if (c == '*') {
stars++; //increment operator. add one to an int var
cout << "Another star";
}
else {
non_stars++;
cout << "Another non star";
}
-------------------------------------------------------------
if (c == '*') {
stars++;
if (stars > 100)
cout << "More than 100 stars";
}
else //matches the outer if
cout << "A non star"; //not counting other chars
-------------------------------------------------------------
if (c == '*') {
stars++;
if (stars > 100) {
again = 'y';
cout << "More than 100 stars";
}
else
cout << "Less than 100 stars";
}
else {
non_stars++;
cout << "Another non star";
}
What happens if any of the }'s are missing?
A program to calculate julian dates julian.cpp (i.e. what day of the year a particular day is).
Next (while)