Skip to main content

Java Tutorial For Beginners: Part 5.

Problem: Java Program To Print Right Triangle Star Pattern
import java.util.*;
public class TrianglePattern1 {

public static void main(String args[]) {
int rows, i, j;

Scanner in = new Scanner(System.in);
System.out.print("Enter The Number Of Rows: ");
rows = in.nextInt();

for(i = 1; i <= rows; i++) {
for(j = 1; j <= i; ++j) { /* prints the rows of triangle */
System.out.print("* ");
}

System.out.print("\n"); /* move to next row */
in.close(); 
}}}

Problem: Java Program To Print Inverted Right Triangle Star Pattern
import java.util.Scanner;
public class TrianglePattern2 {

public static void main(String args[]) {
int rows, i, j;

Scanner in = new Scanner(System.in);
System.out.print("Enter The Number Of Rows: ");
rows = in.nextInt();

for(i = rows; i >= 1; i--) {
for(j = i; j >= 1; j--) { /* prints the rows of triangle */
System.out.print("* ");
}

System.out.print("\n"); /* move to next row */
in.close(); 
}}}

Problem: Java Program To Print Pyramid Pattern of Star Character
import java.util.*;

public class TrianglePattern3 {
public static void main(String args[]) {
int rows, i, space, star=0;

Scanner input = new Scanner(System.in);
System.out.print("Enter The Number Of Rows: ");
rows = input.nextInt();

for(i = 1; i <= rows; i++) { // printing one row in every iteration
for(space = 1; space <= rows-i; space++) { // printing spaces
System.out.print(" ");
}

while(star != (2*i - 1)) {   // printing stars
System.out.print("*");
star++;;
}

star=0;
System.out.print("\n");  // move to next row
input.close();
}}}

Problem: Java Program To Print Inverted Pyramid Pattern of Star Character 
import java.util.*;

public class TrianglePattern4 {
public static void main(String args[]) {
int rows, i, space, star=0;

Scanner input = new Scanner(System.in);
System.out.print("Enter The Number Of Rows: ");
rows = input.nextInt();

for(i = rows; i >= 1; i--) { // printing one row in every iteration
for(space = 1; space <= rows-i; space++) { // printing spaces
System.out.print(" ");
}

while(star != (2*i - 1)) {   // printing stars
System.out.print("*");
star++;;
}

star=0;
System.out.print("\n");  // move to next row
input.close();
}}}

Problem: Java Program To Print Diamond Pattern of Star Character
import java.util.*;

public class TrianglePattern5 {
public static void main(String args[]){

int n, c, k, space=1;

Scanner scan = new Scanner(System.in);
System.out.print("Enter The Number Of Rows (For Diamond Dimension: ");
n = scan.nextInt();

space = n-1;
for(k=1; k<=n; k++){
for(c=1; c<=space; c++){
System.out.print(" ");
}

space--;
for(c=1; c<=(2*k-1); c++){
System.out.print("*");
}
System.out.println();
}

space = 1;
for(k=1; k<=(n-1); k++){
for(c=1; c<=space; c++){
System.out.print(" ");
}

space++;
for(c=1; c<=(2*(n-k)-1); c++){
System.out.print("*");
}
System.out.println();
}
scan.close();
}}