Membuat Segitiga Pascal dengan Java

Ini dia sourcodenya…
import java.util.ArrayList;
import java.util.List;

public class SegitigaPascal {

public static void main(String[] args) {
int n = 10;
int segitiga[][] = new int[n + 1][n + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
segitiga[i][j] = 1;
} else {
segitiga[i][j] = segitiga[i-1][j-1] + segitiga[i-1][j];
}
}
}
List centered = new ArrayList();
for (int i = 0; i <= n; i++) {
String currentRow = "";
for (int j = 0; j <= n; j++) {
if (segitiga[i][j] != 0) {
currentRow += segitiga[i][j] + " ";
}
}
centered.add(currentRow);
}
int longestString = centered.get(n – 1).length() – 1;
for (int i = 0; i < n; i++) {
int longCurrentStr = centered.get(i).length() – 1;
for (int j = 0; j < (longestString – longCurrentStr)/2; j++) {
System.out.print(" ");
}
System.out.println(centered.get(i));
}
}
}
Output:

4 Comments »

  1. jawarif Said:

    ooo…gitu.

  2. ferry Said:

    tapi q cba waktu yang bagian

    int longestString = centered.get(n – 1).length() – 1;
    for (int i = 0; i < n; i++) {
    int longCurrentStr = centered.get(i).length() – 1;
    for (int j = 0; j < (longestString – longCurrentStr)/2; j++) {
    System.out.print(" ");

    kok bermasalah.
    mohon infonya.

  3. Rhizky Said:

    ya’ pa L’ gag usah pakek array
    cz q d kasih tgas gt ??
    segitiga pascal tanpa array

    • wakyong Said:

      Sipp yeah..


{ RSS feed for comments on this post} · { TrackBack URI }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: