Understanding Loops in SAS – DO, DO WHILE, DO UNTIL

Welcome back to Mindful Data Minds! In this session, we’ll explore loops in SAS. Loops allow us to perform repetitive tasks efficiently. SAS provides three main types of loops:

  • DO Loop
  • DO WHILE Loop
  • DO UNTIL Loop

Watch the Full Tutorial

What You Will Learn

  • How to use DO loops for fixed iterations.
  • How DO WHILE checks conditions before execution.
  • How DO UNTIL ensures at least one execution.
  • Practical use cases like EMI and interest calculations.

General Syntax

do <index-variable> = <start> to <end>;
   <statements>;
end;

do while (<condition>);
   <statements>;
end;

do until (<condition>);
   <statements>;
end;

DO Loop

The DO loop executes a block of code a fixed number of times.

Example: Loan Interest Calculation

Suppose a person takes a loan of ₹15,00,000 at 10.5% interest for 60 months, with EMI = ₹32,409. We want to calculate the total interest paid.

data loan_emi_do;
   principal = 1500000;
   rate = 0.105;
   time = 60;
   emi = 32409;
   cum_amount = 0;
   do month=1 to time;
   cum_amount + emi;
   if month=60 then interest_paid = cum_amount - principal;
   output;
   end;
run;

Result: Interest paid = ₹4,44,540 after 60 months.

DO WHILE Loop

The DO WHILE loop checks the condition before executing the block.

data loan_emi_while;
   principal = 1500000;
   rate = 0.105;
   time = 60;
   emi = 32409;
   cum_amount = 0;
   month = 1;
   do while (month<= t);
   cum_amount + emi;
   if month=60 then interest_paid = cum_amount - principal;
   output;
   month+1;
   end;
run;

Produces the same result as DO loop, but condition is checked first.

DO UNTIL Loop

The DO UNTIL loop executes the block at least once, then checks the condition.

data loan_emi_until;
   principal = 1500000;
   rate = 0.105;
   time = 60;
   emi = 32409;
   cum_amount = 0;
   month = 1;
   do until (t<month);
   cum_amount + emi;
   if month=60 then interest_paid = cum_amount - principal;
   output;
   month+1;
   end;
run;

Same result, but note: DO UNTIL always runs at least once, even if the condition is false initially.

Key Difference

  • DO WHILE → Checks condition first, may not run at all.
  • DO UNTIL → Runs once before checking condition, so it always executes at least once.

Next Step

Continue learning by exploring the next tutorial in this series. Also subscribe to get notified about new lessons.

Have a Question?

Drop your doubts in the comments below or contact us.

Leave a Reply

Your email address will not be published. Required fields are marked *