TOC

This article is currently in the process of being translated into Indonesian (~22% done).

Struktur Kontrol:

Loops

Teknik penting lainnya ketika menuliskan sebuah software adalah pengulangan - kempampuan untuk mengulangi sebuah blok dari kode sebanyak x kali. Di C#, ada 4 macam jenis yang berbeda, dan kita akan bahas masing-masing jenisnya.

The while loop

Pengulangan 'while' ini mungkin yang paling sederhana, jadi kita mulai dengan ini. Pengulangan while cukup mengeksekusi sebuah blok kode sepanjang kondisi yang diberikan benar. Contoh kecil, dan penjelasan lebihnya:

using System;

namespace ConsoleApplication1
{
    class Program
    {
static void Main(string[] args)
{
    int number = 0;

    while(number < 5)
    {
Console.WriteLine(number);
number = number + 1;
    }

    Console.ReadLine();
}
    }
}

Coba jalankan kodenya. Anda akan mendapat daftar angka, dari 0 sampai 4. Angka yang pertama didefinisikan sebagai 0, dan pada setiap waktu kode dalam pengulangan dieksekusi, akan ditambahkan satu. tapi mengapa hanya mendapatkan 4, ketika kodenya tertulis 5? Untuk kondisi menghasilkan benar, angka harus kurang dari 5, dalam kasus ini berarti kode itu dimana angka tidak tercapai seketika angka itu sama dengan 5. Ini dikarenakan kondisi pengulangan while dievaluasi sebelum masuk ke blok kode.

The do loop

The opposite is true for the do loop, which works like the while loop in other aspects though. The do loop evaluates the condition after the loop has executed, which makes sure that the code block is always executed at least once.

int number = 0;
do  
{  
    Console.WriteLine(number);  
    number = number + 1;  
} while(number < 5);

The output is the same though - once the number is more than 5, the loop is exited.

The for loop

The for loop is a bit different. It's preferred when you know how many iterations you want, either because you know the exact amount of iterations, or because you have a variable containing the amount. Here is an example of the for loop.

using System;

namespace ConsoleApplication1
{
    class Program
    {
static void Main(string[] args)
{
    int number = 5;

    for(int i = 0; i < number; i++)
Console.WriteLine(i);

    Console.ReadLine();
}
    }
}

This produces the exact same output, but as you can see, the for loop is a bit more compact. It consists of 3 parts - we initialize a variable for counting, set up a conditional statement to test it, and increment the counter (++ means the same as "variable = variable + 1").

The first part, where we define the i variable and set it to 0, is only executed once, before the loop starts. The last 2 parts are executed for each iteration of the loop. Each time, i is compared to our number variable - if i is smaller than number, the loop runs one more time. After that, i is increased by one.

Try running the program, and afterwards, try changing the number variable to something bigger or smaller than 5. You will see the loop respond to the change.

The foreach loop

The last loop we will look at, is the foreach loop. It operates on collections of items, for instance arrays or other built-in list types. In our example we will use one of the simple lists, called an ArrayList. It works much like an array, but don't worry, we will look into it in a later chapter.

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
static void Main(string[] args)
{    
    ArrayList list = new ArrayList();
    list.Add("John Doe");
    list.Add("Jane Doe");
    list.Add("Someone Else");
   
    foreach(string name in list)
Console.WriteLine(name);

    Console.ReadLine();
}
    }
}

Okay, so we create an instance of an ArrayList, and then we add some string items to it. We use the foreach loop to run through each item, setting the name variable to the item we have reached each time. That way, we have a named variable to output. As you can see, we declare the name variable to be of the string type – you always need to tell the foreach loop which datatype you are expecting to pull out of the collection. In case you have a list of various types, you may use the object class instead of a specific class, to pull out each item as an object.

When working with collections, you are very likely to be using the foreach loop most of the time, mainly because it’s simpler than any of the other loops for these kind of operations.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!