Loop Constructs

Kenya has while loops and for loops:

While loops

While loops repeat until the given condition becomes false.

int i = 1;

while ( i <= 10 )
{
  println( i );
  i = i + 1;
}

For loops

For loops count through a certain number of iterations using an index variable. There are two different ways of setting up a for loop. The first has the following syntax:

int i;

for i = 1 to 10 
{
   println( i );
}

prints:

1
2
3
4
5
6
7
8
9
10


for i = 2 to 10 step 2
{
   println( i );
}

prints:

2
4
6
7
8
10

for decreasing i = 10 to 2
{
   println( i );
}

prints:

10
8
6
4
2

The count, here held in i, can increase or decrease with a given step. If these are not specified the default is increasing with step 1.

The other way to declare a for loop is to use a syntax closer to that of Java, as shown in the following examples:

int i;

for ( i = 1 ; i <= 10 ; i++ )
{
  println( i );
}

for ( i = 10; i > 0 ; i-- )
{
  println( i );
}