Wednesday, November 26, 2008

Making Right Angle Triangle

It has been a while since I've post coding in this blog. I was busy with my semester exam and assignments. These code uses for loops to generate a triangle when it is execute.

Here is a sample code that I have done:

import javax.swing.JOptionPane;

public class TriangleMaker

{

public static void main(String[] args)

{

String output = "", num;

int n = 0;

num = JOptionPane.showInputDialog("Enter any number between 1 to 20:");

n = Integer.parseInt(num);

if(n > 0 && n <>

{

nextRow:

for(int row = 1; row <= n; row++)

{

output += "\n";

for(int column = 1; column <= (n * 2); column++)

{

if(column > row)

continue nextRow;

output += "* ";

}

}

JOptionPane.showMessageDialog(null, output, "Triangle Make", JOptionPane.INFORMATION_MESSAGE);

}

else

JOptionPane.showMessageDialog(null, "You have input an invalid value", "Invalid value", JOptionPane.ERROR_MESSAGE);

System.exit(0);

}

}

In this code, the labeled for loop starts at the nextRow label. When the if structure in the inner for loop detects that column is greater than row, the labeled continue statement skips the current iteration of the outer loop marked with the given label. Even though the inner for loop counts greater than the outer loop, the number of * characters output on a row never exceeds the value of row.

No comments: