The basic syntax of a conditional statement is:
if condition1 then
what happens if condition1 passes
end if;
In Ada, any conditional must come after the begin statement and before the end [procedure name] statement.
Choice Between Two Things - If and Else
There is also a way to make a choice between two things - if one condition is not met, then such and such will happen.
The syntax of this is:
if condition1 then
what happens if condition1 passes
else
what happens if condition1 did not pass
end if;
Nested Conditional
The next scenario describes how code will make choices that lead to further choices. These are nested conditionals.
This is the syntax of a nested conditional:
if condition1 then
--condition1 passed, now check if condition2 will
if condition2 then
--condition2 passed
what happens if condition 2 passes
end if;
else
--what happens if condition1 did not pass
if condition3 then
--condition3 passed
what happens if condition 3 passes
end if;
end if;
Compound Conditional
A compound conditional is another way code makes choices. It involves giving two conditions in one, such as checking if number1 is greater than zero AND if number1 is less than two.
There are two ways two write these: using and or or. I will describe the use of these operators in the Logical Operators section.
It would look like this:
if condition1 and condition2 then
what happens if condition1 AND condition2 passes
else
what happens if condition1 OR condition2 did not pass
end if;
Elsif
Another important way of testing is using elsif. This is like an extension if else in that you can provide a condition that you want to be tested if the initial if or previous elsif in the same conditional tree had failed.
The syntax is as follows:
if condition1 then
what happens if condition1 passes
elsif condition2 --IF CONDITION1 FAILED
what happens if condition2 passes
elsif condition3 --IF CONDITION2 FAILED
what happens if condition3 passes
end if;
Logical Operators
The most common operators are:
1) and
2) or
3) not
and is used to test if BOTH conditions are being met. If so, the test will pass, and if not, the test will fail.
or is the opposite in that it checks of EITHER of the conditions are being met. If so, the test will pass. If neither are, it will fail.
not is used for turning a condition in the opposite direction. If the condition is num1 = num2, then using not will turn the condition into num1 /= num2 (num1 does not equal num2).
Code Examples
If-Then
The first is an example of a simple conditional to see if a piece of code is either done or not done (if - then):
The output:
If-Else
This example gives you an idea of how an if-else works in Ada.
The initial condition will fail, causing the else-code to run.
The output:
If-Elsif-Else
The output:
Nested, Compound, Logical Operators
The output:
No comments:
Post a Comment