{"id":355,"date":"2015-11-23T12:56:14","date_gmt":"2015-11-23T01:56:14","guid":{"rendered":"https:\/\/learn-java-by-example.com\/?p=355"},"modified":"2015-12-06T14:32:36","modified_gmt":"2015-12-06T03:32:36","slug":"printing-triangles-java","status":"publish","type":"post","link":"https:\/\/learn-java-by-example.com\/java\/printing-triangles-java\/","title":{"rendered":"Printing Triangles in Java"},"content":{"rendered":"

A common problem many new Java developers is to write a program that prints out a triangle. There a lots of variations on this problem but lets start with a simple case and then have a look at some possible variations.<\/p>\n

Probably the simplest case is a left aligned triangle of stars that looks like this:<\/p>\n

\r\n*\r\n**\r\n***\r\n****\r\n*****\r\n******\r\n*******\r\n********\r\n*********\r\n**********\r\n<\/pre>\n

To solve this we need to break the problem down. Firstly we identify that we need to print 10 lines, we can use a for loop to achieve this.<\/p>\n

\r\nfor (int i=1; i<=10; i++) {\r\n    \/\/ Print a line of the triangle\r\n}\r\n<\/pre>\n

Then we need to work out how to print each line. Each line adds one additional asterisk, in fact the number of stars required is represented by the loop variable i. With this information we can use a nested loop to output the required number of stars.<\/p>\n

Here’s the source code for the complete solution to help you understand how it all fits together. Please study the code and let us know if you have any questions.<\/p>\n

Once it all makes sense have a look at the discussion of a few variations of this problem below.<\/p>\n

\r\npackage com.learnjava.math.triangle;\r\n\r\n\/**\r\n * Write a Java program that prints out a triangle\r\n *\r\n * *\r\n * **\r\n * ***\r\n * etc\r\n *\r\n * @author https:\/\/learn-java-by-example.com\r\n *\r\n *\/\r\n\r\npublic class SimpleTriangle {\r\n\r\n\tpublic static void main(String[] args) {\r\n\r\n\t\t\/\/ Our triangle will have 10 lines\r\n\t\t\/\/ One loop iteration each line\r\n\r\n\t\tfor (int i=1; i<=10; i++) {\r\n\r\n\t\t\t\/\/ For each loop iteration \r\n                        \/\/ we want to print a number of stars\r\n\t\t\t\/\/ 1st line -> 1 star\r\n\t\t\t\/\/ 2nd line -> 2 star\r\n\t\t\t\/\/ ...\r\n\r\n\t\t\tfor (int j=0;j<i; j++) {\r\n\t\t\t\tSystem.out.print("*");\r\n\t\t\t}\r\n\t\t\tSystem.out.println();\r\n\t\t}\r\n\t}\r\n}\r\n\r\n<\/pre>\n

Turn it upside down<\/h2>\n

What if we want to turn our triangle upside down?<\/p>\n

\r\n******\r\n*****\r\n****\r\n***\r\n**\r\n*\r\n<\/pre>\n

We are still printing the same number of lines, so our outer loop stays the same. What changes is the number of stars that are printed for each line.<\/p>\n

Full source code for the Reverse Triangle example is available for download<\/a> to our members. <\/p>\n

Pyramid<\/h2>\n

A common variation is to display the triangle as a (symmetric) pyramid.<\/p>\n

\r\n         *\r\n        ***\r\n       *****\r\n      *******\r\n     *********\r\n    ***********\r\n   *************\r\n  ***************\r\n *****************\r\n*******************\r\n<\/pre>\n

Again the logic is very similar, difference being this time for each line we need to print a number of spaces before printing our stars.<\/p>\n

Full source code for the Pyramid example is available for download<\/a> to our members. <\/p>\n

Numbers instead of Stars\/Asterisks<\/h2>\n

Instead of using stars to print our triangle we may be asked to use numbers. This type of problem generally requires you to implement an additional pattern in the numbers used.<\/p>\n

For example using 0s and 1s, alternating what is used to start the line.<\/p>\n

\r\n0\r\n10\r\n010\r\n1010\r\n01010\r\n101010\r\n<\/pre>\n

Or counting down numbers for each line, and incrementally decreasing what each line starts with.<\/p>\n

\r\n54321\r\n4321\r\n321\r\n21\r\n1\r\n<\/pre>\n
\nFull source code for all the problems discussed above is available for download<\/a> to our members.
\nx<\/span><\/div>\n

Once you mastered these we would suggesting looking at the example covering how to generate a Pascals Triangle<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"

A common problem many new Java developers is to write a program that prints out a triangle. There a lots of variations on this problem but lets start with a simple case and then have a look at some possible variations. Probably the simplest case is a left aligned triangle of stars that looks like…<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true,"jetpack_social_options":[]},"categories":[24,4],"tags":[103,104,6,105,101,102,37],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p6Yyl2-5J","jetpack-related-posts":[{"id":160,"url":"https:\/\/learn-java-by-example.com\/java\/pascals-triangle\/","url_meta":{"origin":355,"position":0},"title":"Pascals Triangle","date":"February 13, 2011","format":false,"excerpt":"Write a Java application that prints the first 10 lines of Pascals Triangle. Each row of a Pascals Triangle can be calculated from the previous row so the core of the solution is a method that calculates a row based on the previous row which is passed as input. Once\u2026","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":222,"url":"https:\/\/learn-java-by-example.com\/java\/list-array\/","url_meta":{"origin":355,"position":1},"title":"Using a List instead of an array","date":"March 8, 2012","format":false,"excerpt":"Lists and arrays can both be used to store ordered collections of data. Both have their strengths and weakness which we shall discuss in a later post. Previously we showed you how to generate Pascals Triangle and in that Java example we used arrays to represent each row of the\u2026","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":199,"url":"https:\/\/learn-java-by-example.com\/java\/pythagoras-theorem\/","url_meta":{"origin":355,"position":2},"title":"Pythagoras Theorem","date":"December 13, 2010","format":false,"excerpt":"One of our member students was asked to implement the Pythagoras Theorem using Java. This is a good opportunity to introduce the Math class which contains a collection of static methods for various mathematical functions. We need the square root method (sort) to calculate the hypotenuse, and can also use\u2026","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":96,"url":"https:\/\/learn-java-by-example.com\/java\/simple-mortgage-calculator\/","url_meta":{"origin":355,"position":3},"title":"Simple Mortgage Calculator","date":"June 5, 2010","format":false,"excerpt":"This example expands on the Monthly Payment Calculator example we posted earlier. As well as calculating the monthly payment for a loan, it then goes on to use that to calculate the balance of the loan after each payment. This is often referred to as an amortisation schedule. The displayMonthlyBalance()\u2026","rel":"","context":"In "Featured"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":238,"url":"https:\/\/learn-java-by-example.com\/java\/selection-sort\/","url_meta":{"origin":355,"position":4},"title":"Selection Sort","date":"June 19, 2015","format":false,"excerpt":"When you are learning Java you are very likely going to be asked to write a program to sort values. We will start with one of the simpler sort algorithms, the Selection Sort (also known as an Exchange Sort). It's not a particularly efficient algorithm and really only suitable for\u2026","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":247,"url":"https:\/\/learn-java-by-example.com\/java\/bubble-sort\/","url_meta":{"origin":355,"position":5},"title":"Bubble Sort","date":"June 30, 2015","format":false,"excerpt":"The Bubble Sort algorithm gets it's name from the fact that on each pass, one element of the array 'bubbles' it's way through to it's correct (sorted) position in the array. Rather than me try and explain the details the following video gives a great visual demonstration of how the\u2026","rel":"","context":"In "Featured"","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/img.youtube.com\/vi\/MtcrEhrt_K0\/0.jpg?resize=350%2C200","width":350,"height":200},"classes":[]}],"_links":{"self":[{"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/posts\/355"}],"collection":[{"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/comments?post=355"}],"version-history":[{"count":5,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/posts\/355\/revisions"}],"predecessor-version":[{"id":374,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/posts\/355\/revisions\/374"}],"wp:attachment":[{"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/media?parent=355"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/categories?post=355"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/tags?post=355"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}