HOW TO PRINT DIAMOND PATTERN USING SINGLE FOR LOOP IN Java

Share Post
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Please Subscribe Youtube| Like Facebook | Follow Twitter

In this tip, we will write Java method that will print diamond pattern using single for loop.

public class Diamond{
    public static void main(String args[]) {
     PrintDiamondSingleLoop(10);
    }
    
private static void PrintDiamondSingleLoop(int row) 
{
    row++;
    int mid = row/2;
    int midLeft = mid;
    int midRight = mid;
    int currentRow = 1;
    int currentColumn = 1;
    for (int i = 1; i <= row * row; i++) 
    {
               
        if(i % row == 0)
        {
            System.out.println("");

            if(currentRow < mid)
            {
                midLeft--;
                midRight++;

            }else
            { 

                midLeft++;
                midRight--;
            }

            currentColumn = 1;
            currentRow++;
        }

        if (currentColumn >= midLeft && currentColumn <= midRight)
        {

           
            System.out.print("*");
        }
        else
        {

           
            System.out.print(" ");

        }
                                  
        currentColumn++;
            
    }
                  
}
    
}
Please Subscribe Youtube| Like Facebook | Follow Twitter


Share Post
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Leave a Reply

Your email address will not be published. Required fields are marked *