90 likes | 292 Views
Nested Loop & Rekursif. Dasar-Dasar Pemrograman. Nested Loop. Logical structure used in computer programming where two repeating statements are placed in a "nested" form. In a nested loop, the first iteration of the outer loop causes the inner loop to execute .
E N D
Nested Loop & Rekursif Marsel Willem Aipassa, S. Kom. Dasar-Dasar Pemrograman
Nested Loop • Logical structure used in computer programming where two repeating statements are placed in a "nested" form. • In a nested loop, the first iteration of the outer loop causes the inner loop to execute. • The inner loop then repeats for as many times as is specified. • When the inner loop completes, the outer loop is executed for its second iteration, triggering the inner loop again, and so on until the requirements for the outer loop are complete. Marsel Willem Aipassa, S. Kom.
Example (Multiply Table) for loop1 := 1 to 6 do begin for loop2 := 1 to 8 do begin write(loop1*loop2,' '); end; writeln(); end; Marsel Willem Aipassa, S. Kom.
Latihan • Membuataplikasi yang akanmemberikan output sepertiberikut: 1 2 3 4 5 … n 1 2 3 4 5 … n 1 2 3 4 5 … n ……… 1 2 3 4 5 … n n kali Marsel Willem Aipassa, S. Kom.
TugasKelas • Buatlah program yang dapatmemberikan output berikutberdasarkaninputann. 1 2 3 4 5 … n 1 2 3 4 5 … n 1 2 3 4 5 … n ……… 1 2 3 4 5 … n n kali Marsel Willem Aipassa, S. Kom.
Recursion • Method of defining functions in which the function being defined is applied within its own definition. • Recursive are typically slower than iterative functions. • Recursive must have a condition to stop. • Not every programming language allows recursion, because it can cause lack of memory. function a(nilai : integer) begin a(3); end; Marsel Willem Aipassa, S. Kom.
Contoh (Penambahanbilangan) • Membuataplikasiuntukmenghitungdenganaturan: • f(n) = f(n)+f(n-1)+f(n-2)+f(n-3) +f(n-4) • Contoh: • f(5) = 5+4+3+2 +1 = 15 Marsel Willem Aipassa, S. Kom.
When should we use iteration, and when use recursion? • There are (at least) these three factors to consider: • Iterative functions are typically faster than their recursive counterparts. So, if speed is an issue, you would normally use iteration. • If the stack limit is too constraining then you will prefer iteration over recursion. • Some procedures are very naturally programmed recursively, and all but unmanageable iteratively. Marsel Willem Aipassa, S. Kom.
Tugas • Buatlahaplikasiuntukmenghitungnilaifaktorialdarisuatubilangan. Dalamperhitungantidakdiperbolehkanmenggunakan operator perkalian, hanyadengan operator penambahandenganmenggunakanNested Looping! Contoh : input = 4 output = 24 (faktorialdari 4) • Buatlahaplikasiuntukmenampilkanderetfibonaci. Tidakdiperbolehkanmenggunakanrumus. GunakanMetodeRekursif. Contoh : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597….. • Kumpulkanbesok jam 2 di lab E201A Marsel Willem Aipassa, S. Kom.