Joseph Haugh
University of New Mexico
void main() {
int x = 3; // First
int y = 5; // Second
IO.println(x + y); // Third
}
int abs(int n) {
if (n < 0) {
return n * -1;
}
return n;
}
void main() {
IO.println(abs(3));
IO.println(abs(-4));
}
If statements have the following syntax:
if (<<booleanExpression>>) {
<<thenStatements>>
}// 2 < 0 is false
if (2 < 0) {
IO.println("In the then branch");
}
// So the else branch is taken
else {
IO.println("In the else branch");
}
String toLetter(int grade) {
if (grade <= 59) {
return "F";
} else if (grade <= 69) {
return "D";
} else if (grade <= 79) {
return "C";
} else if (grade <= 89) {
return "B";
} else {
return "A";
}
}
void main() {
IO.println(toLetter(67)); // D
IO.println(toLetter(91)); // A
IO.println(toLetter(84)); // B
}
boolean validateNumber(int n) {
// Make sure the number is positive
if (n > 0) {
// Also make sure it is even
if (n % 2 == 0) {
// And that is larger than 100
if (n > 100) {
// Then it is validated
return true;
}
}
}
return false;
}
This code:
boolean validateNumber(int n) {
// Make sure the number is positive
if (n > 0) {
// Also make sure it is even
if (n % 2 == 0) {
// And that is larger than 100
if (n > 100) {
// Then it is validated
return true;
}
}
}
return false;
}
Becomes:
boolean validateNumber(int n) {
// Make sure the number is positive
// AND even
// AND greater than 100
if (n > 0 && n % 2 == 0 && n > 100) {
return true;
}
return false;
}
What other improvements could be made?
boolean validateNumber(int n) {
// Make sure the number is positive
// AND even
// AND greater than 100
if (n > 0 && n % 2 == 0 && n > 100) {
return true;
}
return false;
}
We could remove the redundant n > 0 check
boolean validateNumber(int n) {
// Make sure the number is even
// AND greater than 100
if (n % 2 == 0 && n > 100) {
return true;
}
return false;
}
You will often be tempted to write code such as this:
if (someCondition) {
return true;
}
return false;This is redundant as you are checking the condition (someCondition)
Then if it is true you return true
Otherwise, you return false
Well why not just return the condition?!
return someCondition;Can we apply the check boolean return boolean rule here?
boolean validateNumber(int n) {
// Make sure the number is even
// AND greater than 100
if (n % 2 == 0 && n > 100) {
return true;
}
return false;
}
Yes!
boolean validateNumber(int n) {
// Make sure the number is even
// AND greater than 100
return n % 2 == 0 && n > 100;
}
int i = 0;
// Do loop body while
// i is less than 10
while (i < 10) {
IO.println(i);
i += 1;
}
while (<<booleanCondition>>) {
<<<bodyStatements>>>
}
void countdown(int n) {
int i = n;
while (i >= 0) {
IO.println(i);
i -= 1;
}
}
void main() {
countdown(10);
countdown(0);
countdown(-7);
}