SAS-Loop
In general programming, the statements are executed sequentially, i.e., thefirst statement of a program is executed first, then the second, and so on. However, there may be a situation when we need to execute the same set of statements for a specific number of times or repeatedly. In this type of case, we need to use Loops.
In SAS, we can use loops by using Do Statement,which is also called Do Loop.
There are three basic Loops used in SAS programming:
- Do Loop
- Do Until
- Do While
Now,let’s understand the actions of these Loops in the SAS programming:
Do Loop
It is the simplest form of DO loops. The action of the DO loop is unconditional, which means that if we instruct the loop to execute a statement for 50 times, then it will execute that statement for 50 times without any restriction (unless there is anerroroccurs during processing). Let’s take an example to understand it’s working.
Example:
Here, we are taking an example ofincremental bank account balanceand going to calculate the account balanceafter the next 4payments of Rs.1000.
Assuming that the initial account balance is 9000,so we can assign “Balance = 9000” in the belowcode.
In this code, we are executing the statement”balance + 1000″, for 4 times so that it will execute up to 4 times unconditionally.
Execute the above code in SAS Studio:
Output:
As we can see in the output,there are two variables:
- The first variable is “balance,” which containsthe account balance after 4 payment i.e., 13000.
- The second variable is “i,” which is showing the final value of i after completion of all iterations.
Do Until
The second type of loop is DO UNTIL loop. We can use this loop to continue execution of statementsuntila condition becomes true. Let’s understand through an example:
Example:
Here we are going to calculate the number of payments for a loan by using DO UNTIL loop. Suppose the total amount of loan is 30,000, and payment is Rs. 1000per month.
Execute the above code in SAS studio:
Output:
As per the above output, the counting of payments continues until the loan becomes zero.
Do While
The third type of Loop is DO WHILE loop. We can use this loop to continue execution while the specified condition remains true. Let’s understand through an example:
In this example,we are going to calculate the number of payments for the loan by using DO WHILE loop. Here we are using the same data asof the above example.
Execute the above code in SAS studio:
Output:
As per the above output, the counting of payments continues until the loan is greater than zero or the condition remains true.
In both loops described above, we can give condition as per our requirement by using various logical and comparison operators.
Note: We have learned these operators in the previous topic of SAS Operator.