*Tinggi piramida ditentukan oleh user
Membuat Piramida Menggunakan Perulangan While:
Kode:
import java.util.Scanner; public class latihan1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Masukkan tinggi piramida: "); int tinggi = input.nextInt(); int i = 1; while (i <= tinggi){ int j = i; while (j <= (tinggi-1)){ System.out.print("-"); j++; } int k = 0; while (k <= (i*2) - 2){ System.out.print("x"); k++; } System.out.println(i); i++; } } }
Output:
Masukkan tinggi piramida: 15 --------------x1 -------------xxx2 ------------xxxxx3 -----------xxxxxxx4 ----------xxxxxxxxx5 ---------xxxxxxxxxxx6 --------xxxxxxxxxxxxx7 -------xxxxxxxxxxxxxxx8 ------xxxxxxxxxxxxxxxxx9 -----xxxxxxxxxxxxxxxxxxx10 ----xxxxxxxxxxxxxxxxxxxxx11 ---xxxxxxxxxxxxxxxxxxxxxxx12 --xxxxxxxxxxxxxxxxxxxxxxxxx13 -xxxxxxxxxxxxxxxxxxxxxxxxxxx14 xxxxxxxxxxxxxxxxxxxxxxxxxxxxx15Anda dapat memodifiskasi program tersebut agar sisi kanan dengan sisi kiri memiliki tanda(-) yang sama
Kode:
import java.util.Scanner; public class latihan1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Masukkan tinggi piramida: "); int tinggi = input.nextInt(); int i = 1; while (i <= tinggi){ int j = i; while (j <= (tinggi-1)){ System.out.print("-"); j++; } int k = 0; while (k <= (i*2) - 2){ System.out.print("x"); k++; } int l=i; while (l <= (tinggi-1)){ System.out.print("-"); l++; } System.out.println(""); i++; } } }Output:
Masukkan tinggi piramida: 10 ---------x--------- --------xxx-------- -------xxxxx------- ------xxxxxxx------ -----xxxxxxxxx----- ----xxxxxxxxxxx---- ---xxxxxxxxxxxxx--- --xxxxxxxxxxxxxxx-- -xxxxxxxxxxxxxxxxx- xxxxxxxxxxxxxxxxxxx
Anda juga dapat menghilangkan tanda(-) disamping piramida dengan memodifikasi kode diatas dibagian:
Kode:
... while (j <= (tinggi-1)){ System.out.print("-"); j++; } ...Menjadi:
... while (j <= (tinggi-1)){ System.out.print(" "); j++; } ...
Output:
Masukkan tinggi piramida: 10 x xxx xxxxx xxxxxxx xxxxxxxxx xxxxxxxxxxx xxxxxxxxxxxxx xxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx
Baca juga cara membuat piramida menggunakan perulangan do-While
No comments:
Post a Comment