Click here to Skip to main content
15,512,419 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
print a combined diagonal star pattern using only for loops as given below:
    *
   * *
  *   *
 *     *
*       *


What I have tried:

Java
package com.packages;

public class star9 {
    public static void main(String args[]) {
        int i, j, k, l,m;
        for (i = 1; i <= 4; i++) {
            for (j = 3; j >= i; j--) {
                System.out.print(" ");
            }
            for(k=i;k<=i;k++){
                System.out.print(" *");
            }
            for(l=2;l<=(i*2);l++){
                System.out.print(" ");
            }
            for(m=i;m>=i;m--){
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
Posted
Updated 4-Dec-21 7:40am
v2
Comments
Gerry Schmitz 4-Dec-21 12:31pm    
It's 9x5.
In the first row, print one in the middle (....*).
In the 2nd, print two * with a -1 and +1 offset from the middle (...*.*...).
etc.
Sweccha Ranjan 4-Dec-21 12:36pm    
can u please provide me with the code..I havent understood
Dave Kreskowiak 4-Dec-21 14:24pm    
Nobody is going to write your code for you. That doesn't help you at all. You're missing the most important part of problem solving, thinking about the problem.

1 solution

Start by writing a method that takes two parameters to print: "blanks before star" and "blanks after star".

Test that, make sure it works.
then it's simple: you just need a single loop that calls it with varying numbers: (5, 0), (4, 1), (3, 3), (2, 5), (1, 7), (0, 9)

Give it a try: it's not complicated if you spend a short time thinking before you launch into code.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900