1 Dasar Pemrograman
Anik Vega Vitianingsih, S.Kom.,MT
KONSEP PERULANGAN
System.out.print(“Vega\n");
System.out.print(“Vega\n");
System.out.print(“Vega\n");
System.out.print(“Vega\n");
System.out.print(“Vega\n");
System.out.print(“Vega\n");
System.out.print(“Vega\n");
System.out.print(“Vega\n");
System.out.print(“Vega\n");
System.out.print(“Vega\n");
2
PERULANGAN (LOOPING) DI JAVA
for while
do - while
3
RUMUS PERULANGAN FOR
for (inisialisasi; kondisi; iterasi) {
statement1;
statement2;
...
}
dimana:
inisialisasi : inisialisasi dari variabel loop.
5
CONTOH IMPLEMENTASI: FOR
Output 0
int i; 1
2
for (i = 0; i < 10; i++) { 3
System.out.println(i); 4
5
} 6
7
8
9
for(int i = 0; i < 10; i++) {
System.out.print(“Vega\n");
}
7
NESTED FOR (PERULANGAN FOR BERSARANG)
int i,j;
for (i=1;i<=5;i++){
for (j=1;j<=i;j++){
System.out.print(i+" ");
}
System.out.println();
}
Output :
1
22
333 8
4444
55555
class BintangKiri {
public static void main(String args[]){
int batas = 5;
for(int i=1; i<=batas; i++){
for(int j=1; j<=i; j++){
System.out.print("*");
}
System.out.println("");
}
}
}
public class BintangKolom{
public static void main(String [] args){
int Kolom=5;
int Baris=5;
for(int i=1;i<=Kolom;i++){
for(int j=1;j<=Baris;j++){
System.out.print("*");
}
System.out.println();
}
}
}
RUMUS PERULANGAN WHILE
inisialisasi;
while( kondisi ){
statement1;
statement2;
...
iterasi;
}
inisialisasi : inisialisasi dari variabel loop.
kondisi : membandingkan variabel inisialisasi pada nilai
batas.
iterasi : melakukan update iterasi → menggunakan
operasi increment atau decrement
Statement di dalam while loop akan dieksekusi
berulang-ulang selama kondisi bernilai benar. 11
CONTOH IMPLEMENTASI WHILE
Output 0
int i = 0; 1
2
while (i < 10) { 3
System.out.println(i); 4
5
i++;
6
} 7
8
9
int i = 1;
while (i <= 10) {
System.out.print("Data Ke-" + i + "=" + "Vega");
i++;
System.out.print("\n");
}
12
Contoh 1
int i = 4;
while ( i > 0 ){
System.out.print(i);
i--;
}
Contoh 2 Contoh 3:
while(true) int x = 0;
System.out.println(“hello”); while (x<10)
{
System.out.println(x);
x++;
}
Contoh 4:
//no loops
while (false)
System.out.println(“hello”);
RUMUS PERULANGAN DO-WHILE
inisialisasi;
do{
statement1;
statement2;
...
iterasi;
} while(kondisi);
14
RUMUS PERULANGAN DO-WHILE
int i = 0; Output
do { 0
System.out.println(i); 1
2
i++; 3
}while(i<10); 4
5
6
7
8
int i = 1; 9
do {
System.out.print("Data Ke-" + i + "=" + "Vega");
i++; 15
} while (i <= 10);
c/ 1
do{
System.out.println(“hello”);
} while (true);
c/ 2:
int x = 0;
do
{
System.out.println(x);
x++;
}while (x<10);
c/ 3:
do
System.out.println(“hello”);
while (false);
CONTOH: PERBANDINGAN WHILE DAN DO-WHILE
Contoh A Contoh B