Perulangan while

Julia Tingkat Menengah

Anthony Markham

Quantitative Developer

Perulangan while - sintaks

  • Kurang umum dibanding for, tetapi berguna dalam beberapa kasus.
  • Ulangi expression selama condition bernilai true.
  • Sering dipakai untuk mengulang aksi hingga kondisi terpenuhi.
while condition
    expression
end
Julia Tingkat Menengah

Perulangan while - contoh

  • Ulangi rangkaian aksi hingga kondisi bernilai true
counter = 10
while counter != 0
    print(counter, " ")
    counter = counter - 1
end
10 9 8 7 6 5 4 3 2 1
Julia Tingkat Menengah

Perulangan while - iterasi pertama

# First iteration
counter = 10
while counter != 0  # counter = 10 here, so this is true
    print(counter, " ")  # print counter, equal to 10
    counter = counter - 1  # decrease the value of counter by 1
end
10
Julia Tingkat Menengah

Perulangan while - iterasi kedua

# Second iteration
counter = 10
while counter != 0  # counter now = 9 here, so this is true
    print(counter, " ")  # print counter, equal to 9
    counter = counter - 1  # decrease the value of counter by 1
end
10 9
Julia Tingkat Menengah

Perulangan while - iterasi ketiga

# Third iteration
counter = 10
while counter != 0  # counter now = 8 here, so this is true
    print(counter, " ")  # print counter, equal to 8
    counter = counter - 1  # decrease the value of counter by 1
end
10 9 8
Julia Tingkat Menengah

Perulangan while - loop tak berujung

  • Apa yang terjadi jika kita lupa menurunkan nilai variabel counter?
# Second iteration
counter = 10
while counter != 0  # counter now = 9 here, so this is true
    print(counter, " ")  # print counter, equal to 9
end
10 10 10 10 10 10 10 10 10
Julia Tingkat Menengah

Perulangan while - penghentian

  • Di lingkungan DataCamp, loop tak berujung akan memutus sesi
  • Di mesin lokal Anda, hentikan program Julia dengan Ctrl + C
Julia Tingkat Menengah

Ayo berlatih!

Julia Tingkat Menengah

Preparing Video For Download...