Conditional statements in programming define conditions under which certain functions are performed. Conditional statements use logical expressions that are evaluated and return a value of either true or false. There are three primary conditional statements:
• If statement • Switch statement • Ternary operators
All these statements are evaluated using operators.
If
The if statement is the simplest control statement. It checks whether a condition is true or false. If the condition is satisfied, all the code within the braces '{}' is executed. The syntax for an if statement is as follows:
if (condition) {
//if true these statements are executed }
The following is an example of an if statement. If the variable a is greater than 10, the value of a will be printed to the screen.
if (a > 10) {
print a; }
The following is an example of an if statement using multiple expressions to evaluate the condition.
if((a < 5) || (a > 10)) {
print a; }
If...else
An if statement checks for only one possibility and ignores all other conditions. An if…else statement checks one condition and if true, the block of code is executed. Otherwise, an alternative statement is executed. The syntax for an if…else statement is as follows:
if (condition) {
//if true these statements are executed }
else {
//if false these statements are executed } int i = 12; int j = 10; int max; if (i > j) { max = i; } else { max = j; }
The previous conditional formulas allow for only two alternative outcomes. A program might have to check more than two alternatives. To check for multiple alternatives, you can use an if…else...if statement. The syntax for this statement is as follows: if (condition1) { //statement1 } else { if (condition2) { //statement2 } else { //statement3 } }
The system checks condition 1 first, and if satisfied, statement1 is executed. If the condition 1 is not satisfied, it moves to condition2. If condition2 is satisfied, statement2 is executed. If condition2 is not satisfied, then statement3 executes. You can use as many conditions as necessary.
You might need to have a condition in a condition. You can do this using nested if statements.
A mathematics teacher uses the following criteria to determine who passes or fails the class:
• Pass the final exam
• Pass the homework sections Check the logic in the following order:
1. If the student has failed the exam, then the student fails the course. 2. If the student has passed the exam, then check the student's
homework sections.
3. If the student has passed the exam and the homework sections, the student passes the course.
4. Otherwise, the student fails.
boolean passExam = true; boolean passHomeWork = false; str studentStatus; if (passExam == true) { if (passHomeWork == true) { studentStatus = "Passed"; } else { studentStatus = "Failed"; } } else { studentStatus = "Failed"; }
Ternary Operator
This conditional statement behaves exactly like an if…else statement. The main reason to use the ternary operator is convenience in coding. Its syntax is as follows:
The condition is checked first and if true, statement1 is executed, if false, statement2 is executed. However, the two expressions following the question mark (?) must be of the same data type.
This example using the ternary operator, is equivalent in logic and results to the previous example using the if...else statement.
int i = 12; int j = 10; int max;
max = i > j ? i : j;
Switch
A switch statement acts as a multi-branch control statement that defines an expression and whose result leads to a specific program execution. The switch statement considers the result and executes code, depending on possible outcomes of the expression. These are known as cases. Each of these cases is listed in the body of the statement.
Following the colon after each case are statements that execute if the expression satisfies the case. There can be any number of statements following a case in a
switch statement. The body of a switch statement is enclosed in braces '{}'. The
following shows the syntax for a switch statement:
switch (expression) { case 'Choice1': Statement1; Statement2; break; case 'Choice2': Statement3; break; case 'Choice3': Statement4; Statement5; Statement6; break; default : DefaultStatement; }
The break; statement tells the program to leave the switch statement and continue immediately after the switch. This can also be used elsewhere in X++ coding. The default case executes if the result of the expression does not match any of the cases. Using the default case is optional.
The following example compares a switch statement with an if…else statement. For these examples, students receive a score from a test. The score must have a corresponding letter grade. The scores can only be 90, 80, 70, and so on.
int score = 80; str grade; str message; switch (score) {
case 90 : grade = "A";
message = "Excellent"; break; case 80 : grade = "B"; message = "Good"; break; case 70 : grade = "C"; message = "Average"; break; case 60 : grade = "D"; message = "Poor"; break;
default : grade = "Failed!";
message = "You need to study more!" ; }
This example produces the same result as the previous example, but uses if...else statements instead of the case statement. Note the number of lines of code and the ease of reading the code in each case.
int score = 80; str grade; if (score == 90) { grade = "A"; } else { if (score == 80) { grade = "B"; } else { if (score == 70) { grade = "C"; } else {
if (score == 60) { grade = "D"; } else { grade = "Failed!"; } } } }
As illustrated on the previous page, the switch statement simplifies the code and makes the program flow more efficiently. Another advantage of using a switch statement is allocating multiple results of the expression to one outcome or case. The following example shows the use of multiple expressions in a switch statement.
str color = "red"; str colortype; switch (color) {
case "red", "yellow", "blue" : colortype = "Primary Color"; break;
case "purple", "green", "orange" : colortype = "Secondary Color"; break;
default : colortype ="Neither Primary or Secondary"; }
This example produces the same result as the previous example, but uses if...else statements instead of the case statement. Note the number of lines of code and the ease of reading the code in each case.
str color = "red"; str colortype; if ((color =="red") || (color =="yellow") || (color =="blue")) {
colortype ="Primary Color"; } else { if ((color =="purple") || (color =="green"') || (color =="orange")) {
colortype ="Secondary Color";
}
else {
colortype ="Neither Primary or Secondary color" }
}
Loops
Repetitive statements, also known as loops, conditionally control data input and output. There are three main loops in X++:
• While loop • Do while loop • For statement
While
The while loop evaluates a condition and executes statements, depending on whether the condition is satisfied. The loop continues to check the condition, and as long as the condition is true, it continues to execute the statements. As soon as the condition becomes false, the statement is exited. The syntax is as follows:
while (condition) {
//statement; }
This is a simple while statement that counts from 1 to 5.
int counter = 1; while (counter <= 5) {
print counter;
counter ++; // This increments the counter by 1 } pause; Result: 1 2 3 4 5
HINT: The previous example uses the counter++ which can increment any
integer by 1. You can also set the increment to any value by using the
variable+=<# to increment> syntax. For example:
counter+=2; //This increments the counter variable by two every time.
Notice the condition is evaluated before the statements are executed. In the previous example, it means that if the counter variable is greater than five when it reaches this loop, it does not execute. Therefore, a while statement can be
executed zero or more times.
Do...while
The function of a do while statement is almost identical to the while statement. The main difference is that the condition is evaluated after the statement
executes. The effect is that the loop always runs at least one time. The following is the syntax for a do while statement:
do {
//statement; }
For
The for statement uses an incrementing counter variable, and a condition, to determine the how long it will continue to loop. The parameters in a for statement include three elements:
• The initial value of the variable.
• The condition under which the loop will continue. • The amount the variable is increased or decreased by. The syntax can be defined as follows:
for ( initial value ; condition ; increment) {
//statement; }
For loops are frequently used when navigating through an array. The following
is an example of how to use a for loop to print each element of a string array called 'abc' that contains 10 strings:
for (counter = 1; counter <= 10; counter++) {
print abc[counter]; }
A for loop and a while loop perform the same function. However, the for loop is more condensed in structure. In a while loop, if the counter variable is not incremented, an infinite loop can occur. This is not possible with a for loop because you receive a syntax error if that part of the condition is not qualified.