Previous Topic Next topic Print topic


Loops - in COBOL and Java

Loops in Managed COBOL

*> Pre-test loops:
declare c1 as binary-long.
perform until c >= 10
   add 1 to c
end-perform
 
perform varying c as binary-long from 2 by 2 until c > 10
   display c2
end-perform
 
*>Post-test loops:
declare c3 as binary-long.
perform with test after until c3 >= 10
   add 1 to c3
end-perform
 
*> Array or collection looping
01 names string occurs any.
set content of names to ("Rod" "Jane" "Fred")
perform varying s as string through names
   display s
end-perform
 
*> Breaking out of loops:
01 i1 binary-long value 0.
perform until exit
   if i1 = 5
      exit perform
   end-if
   add 1 to i1
end-perform
 
*> Continue to next iteration:
declare i2 binary-long value 0
perform varying i2 from 0 by 1 until i2 >= 5
   if i2 < 4
      exit perform cycle
   end-if
   display i2 *>Only prints 4
end-perform

Loops in Java

// Pre-test Loops
int c1;
while (c1 < 10) 
{
   c1++;
}
			  
for (int c2 = 2; c2 <= 10; c2 += 2) 
{
   System.out.println(c2);
}
			 

// Post-test Loop
int c3;
do
{ 
  c3++; 
} while (c3 < 10);
			 
			 
// Array or collection looping
String[] names = {"Rod", "Jane", "Freddy"};
for (int i1 = 0; i1 < names.length; i1++)
{
  System.out.println(names[i1]);
}
			 
			 
// Breaking out of loops
int i2 = 0;
while (true) 
{
  if (i2 == 5) 
  {
      break;
  }
  i2++;
}

// Continue to next iteration
for (int i = 0; i < 5; i++) 
{
  if (i < 4)
  {
    continue;
  }
  System.out.println(i);   // Only prints 4
}

Portions of these examples were produced by Dr. Frank McCown, Harding University Computer Science Dept, and are licensed under a Creative Commons License.

Previous Topic Next topic Print topic