Drawing stars up and down - java

I want to get this result, where _ space characters :
*___*
_*_*_
__*__
public static void main(String args[]) {
int level = 2; // quantity line
int stars = 5; //quantity drawing stars
for(int i = 1;i <= level ; i++){
for(int j =1 ;j <= i; j++){
System.out.print(" ");
}
System.out.println("*");
}
}
So far, I have drawn,
*__
_*_
__*
And I don't know how to draw up ?

Steps to solve these type of questions:
consider * as 1 and spaces as 0. Now i need this output :
10001
01010
00100
first 1 is appearing according to row no. Row 0 - 1 at Col 0, Row 1 - 1 at Col 1
Second 1 is appearing at (total columns-current Row index-1)
print 1 for above two condition otherwise zero.
int rows=3; // quantity line
int cols=5; //quantity drawing stars
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
int k=cols-i-1;
if(i==j || j==k)
System.out.print("*");
else System.out.print(" ");
}
System.out.println();
}

int size=10; // Only one parameter is required which is quantity drawing stars
int length= size%2==0?size/2:size/2+1; // in case of odd one more line need to be print at last on which one Asteric appears.
for (int i = 0; i < length; i++) {
for (int j = 0; j < size; j++) {
if (i == j || i + j == size - 1) { //condition for diagonals
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
Output :
when size = 10;
* *
* *
* *
* *
**
when size = 11
* *
* *
* *
* *
* *
*

You can try below code and output is what you want..
for(int i=3;i>=1;i--)
{
for(int j=i;j<3;j++)
{
System.out.print(" ");
}
for(int j=1;j<=(2*i-1);j++)
{
if(j==1 || j==(2*i-1))
System.out.print("*");
else
System.out.print(" ");
}
System.out.println("");
}

Related

i want to figure out what's wrong in my code

I want to make a java pattern like this using while loops
* * * *
* * *
* *
*
and here is my code
int i = 4;
int j = 0;
while (i >= 0) {
while (j < i) {
System.out.print(" * ");
j++;
}
System.out.print("\n");
i--;
}
but its giving output like this:
* * * *
Does anyone knows what to do....?
TRY CONSIDERING THIS ONE MIGHT HELP YOU !!
Using FOR Loop
public class DownwardTrianglePattern {
public static void main(String[] args) {
int rows = 4;
//outer loop
for (int i = rows-1; i >= 0 ; i--) {
//inner loop
for (int j = 0; j <= i; j++) {
//prints star and space
System.out.print("*" + " ");
}
//throws the cursor in the next line after printing each line
System.out.println();
}
}
}
Using While Loop
public class Itriangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter N : ");
int n = sc.nextInt();
System.out.print("Enter Symbol : ");
char c = sc.next().charAt(0);
int i = n, j;
while(i > 0) {
j = 0;
while(j++ < i) {
System.out.print(c);
}
System.out.println();
i--;
}
}
}
After i--;
you can j=0;
The problem in your code is that in first iteration after completing both the while loops the value of variables is i=3 and j=4. So for the next iteration the first while loop will run as the condition is true i.e. 3>=0 but for the next while loop the condition will be false as j i.e. 3 not less than i i.e. 3. So that's why the next loop does not executes and you are getting that output.
The j needs to be initialized inside loop.
I changed the code as below. it's giving correct output
int i = 4;
while (i >= 0) {
int j = 0;
while (j < i) {
System.out.print(" * ");
j++;
}
System.out.print("\n");
i--;
}
please reset j after j loop
int i = 4;
int j = 0;
while (i >= 0) {
while (j < i) {
System.out.print(" * ");
j++;
}
j = 0;
System.out.print("\n");
i--;
}
when you're finished with inner loop you have to reset j value else it's value will remain 4 which is not less then i value. you can reset the value before starting inner while
int i = 4;
int j = 0;
while (i >= 0) {
j = 0;
while (j < i) {
System.out.print(" * ");
j++;
}
System.out.println(""); // println will work same as System.out.print("\n") in this scenario
i--;
}
By the way your problem can be nicely solved using recursion
public static void main(String[] args) {
printLine(4);
}
private static void printLine(int numberOfStars) {
if(numberOfStars == 0) {
return;
}
System.out.println("* ".repeat(numberOfStars));
printLine(numberOfStars - 1);
}
Output
* * * *
* * *
* *
*

Empty diamond shape with numbers

So I have been asked this question and I could only solve the top part of the code, I am stuck on the bottom part.
Write a Java program called EmptyDiamond.java that contains a method that takes an integer n and prints a empty rhombus on 2n − 1 lines as shown below. Sample output where n = 3:
1
2 2
3 3
2 2
1
Here's my code so far:
public static void shape(int n) {
//TOP PART
for (int i = 1; i <= (n - 1); i++) {
System.out.print(" ");
}
System.out.println(1);
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= (n - i); j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= 2 * i - n + 1; j++) {
System.out.print(" ");
}
System.out.println(i);
}
//BOTTOM PART (The messed up part)
for (int i = n + 1; i <= 2 * n - 2; i++) {
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= n; j++) {
System.out.print(" ");
}
System.out.print(i);
}
for (int i = 1; i <= (n - 1); i++) {
System.out.print(" ");
}
System.out.println(1);
}
public static void main(String[] args) {
shape(4);
}
Maybe a little bit late, but because the bottom part of your message is just the first part mirrored you can use a Stack to print the message in reverse order:
public static void main(String[] args) {
int maxNumber = 3;
Stack<String> message = new Stack<>();
// upper part
for (int row = 0; row < maxNumber; row++) {
int prefix = maxNumber - (row + 1);
int spaces = row >= 2 ? row * 2 - 1 : row;
String line = getLine(row, prefix, spaces);
System.out.println(line);
if (row != maxNumber - 1)
message.add(line);
}
// bottom part
while (!message.isEmpty())
System.out.println(message.pop());
}
public static String getLine(int row, int prefix, int spaces) {
StringBuilder line = new StringBuilder("_".repeat(prefix));
line.append(row + 1);
if (row != 0) {
line.append("_".repeat(spaces));
line.append(row + 1);
}
return line.toString();
}
Output:
__1
_2_2
3___3
_2_2
__1
You can of course use any method you want to fill the stack (i.e. to generate the upper part of your message) like with the method this question suggessted. This upper part I describe contains the first line (inclusive) up to the middle line (exclusive).
Here is the program for printing empty diamond:
int n = 3; //change the value of n to increase the size of diamond
int upperCount = 1;
for (int i = n; i >= 1; i--) {
for (int j = i; j >= 1; j--) {
System.out.print(" ");
}
System.out.print(upperCount);
for (int j = 0; j <= upperCount - 2; j++) {
System.out.print(" ");
}
for (int j = 0; j <= upperCount - 2; j++) {
System.out.print(" ");
}
if (upperCount != 1) {
System.out.print(upperCount);
}
upperCount++;
System.out.print("\n");
}
int lowerCount = n - 1;
for (int i = 1; i <= n - 1; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(" ");
}
System.out.print(lowerCount);
for (int j = 0; j <= lowerCount - 2; j++) {
System.out.print(" ");
}
for (int j = 0; j <= lowerCount - 2; j++) {
System.out.print(" ");
}
if (lowerCount != 1) {
System.out.print(lowerCount);
}
lowerCount--;
System.out.print("\n");
}
Do following changes in the Bottom Part of your code:
int lowerCount = n - 1;
for (int i = n - 1; i >= 2; i--) {
for (int j = 1; j <= (n - i); j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= lowerCount; j++) {
System.out.print(" ");
}
System.out.print(i);
lowerCount -= 2;
}
You can print an empty diamond shape with numbers using two nested for loops over rows and columns from -n to n. The diamond shape is obtained when iAbs + jAbs == n:
int n = 2;
for (int i = -n; i <= n; i++) {
// absolute value of 'i'
int iAbs = Math.abs(i);
for (int j = -n; j <= n; j++) {
// absolute value of 'j'
int jAbs = Math.abs(j);
// empty diamond shape
System.out.print(iAbs + jAbs == n ? jAbs + 1 : " ");
if (j < n) {
System.out.print(" ");
} else {
System.out.println();
}
}
}
Output:
1
2 2
3 3
2 2
1
You can separately define width and height:
int m = 4;
int n = 2;
int max = Math.max(m, n);
for (int i = -m; i <= m; i++) {
// absolute value of 'i'
int iAbs = Math.abs(i);
for (int j = -n; j <= n; j++) {
// absolute value of 'j'
int jAbs = Math.abs(j);
// empty diamond shape
System.out.print(iAbs + jAbs == max ? jAbs + 1 : " ");
if (j < n) {
System.out.print(" ");
} else {
System.out.println();
}
}
}
Output:
1
2 2
3 3
3 3
2 2
1
See also:
• Filling a 2d array with numbers in a rhombus form
• How to print a diamond of random numbers?
java-11
Using String#repeat introduced as part of Java-11, you can do it using a single loop.
public class Main {
public static void main(String[] args) {
int n = 3;
for (int i = 1 - n; i < n; i++) {
int x = Math.abs(i);
System.out.println(" ".repeat(x) + (n - x)
+ " ".repeat(Math.abs((n - x) * 2 - 3))
+ ((i == 1 - n || i == n - 1) ? "" : (n - x)));
}
}
}
Output:
1
2 2
3 3
2 2
1
You can print a variant of the diamond simply by increasing the amount of space by one character:
public class Main {
public static void main(String[] args) {
int n = 3;
for (int i = 1 - n; i < n; i++) {
int x = Math.abs(i);
System.out.println(" ".repeat(x) + (n - x)
+ " ".repeat(Math.abs((n - x) * 2 - 3))
+ ((i == 1 - n || i == n - 1) ? "" : (n - x)));
}
}
}
Output:
1
2 2
3 3
2 2
1
Alternative solution:
public static void main(String[] args) {
int n = 7;
for (int i = -n; i <= n; i++) {
for (int j = -n; j <= n; j++) {
// edge of the diamond
int edge = Math.abs(i) + Math.abs(j);
// diamond shape with numbers
if (edge == n) System.out.print(n - Math.abs(i) + 1);
// beyond the edge && in chessboard order || vertical borders
else if (edge > n && (i + j) % 2 != 0 || Math.abs(j) == n)
System.out.print("*");
// empty part
else System.out.print(" ");
}
System.out.println();
}
}
Output:
** * * 1 * * **
* * * 2 2 * * *
** * 3 3 * **
* * 4 4 * *
** 5 5 **
* 6 6 *
*7 7*
8 8
*7 7*
* 6 6 *
** 5 5 **
* * 4 4 * *
** * 3 3 * **
* * * 2 2 * * *
** * * 1 * * **
See also: How to print a given diamond pattern in Java?
Solution: Java program called EmptyDiamond.java that contains a method that takes an integer n and prints a empty rhombus on 2n − 1 lines.
public class EmptyDiamond {
public static void main(String[] args) {
shape(3); // Change n to increase size of diamond
}
public static void shape(int n) {
int max = 2 * n - 1; // length of the diamond - top to bottom
int loop = 0; // with of each loop. initialized with 0
for (int i = 1; i <= max; i++) {
int val = 0;
if (i <= n) {
loop = n + i - 1;// e.g. when i = 2 and n = 3 loop 4 times
val = i; // value to be printed in each loop ascending
} else {
loop = n + (max - i); //e.g. when i = 4 and n = 3 loop 4 times
val = max - i + 1; // value to be printed in each loop descending
}
for (int j = 1; j <= loop; j++) {
// (value end of loop)
// || (value in the beginning when i <= n)
// || (value in the beginning when i > n)
if (j == loop
|| j == (n - i + 1)
|| j == (n - val + 1)) {
System.out.print(val); // Print values
} else {
System.out.print(" "); // Print space
}
}
System.out.println(); // Print next line
}
}
}
Output when n = 3:
1
2 2
3 3
2 2
1
Stream-only function:
public static void printEmptyDiamond(int n) {
IntStream.range(1, 2*n)
.map(i-> i > n ? 2*n-i : i)
.mapToObj(i -> " ".repeat(n-i) + i + (i>1 ? " ".repeat(2*(i-1)-1)+i : ""))
.forEach(System.out::println);
}
Example output (printEmptyDiamond(7)):
1
2 2
3 3
4 4
5 5
6 6
7 7
6 6
5 5
4 4
3 3
2 2
1
With explainations:
public static void printEmptyDiamond(int n) {
IntStream.range(1, 2*n)
.map(i-> i > n? 2*n-i : i) // numbers from 1 to n ascending, then descending to 1 again
.mapToObj(i -> " ".repeat(n-i) // leading spaces
+ i // leading number
+ (i>1 ? // only when number is > 1
" ".repeat(2*(i-1)-1) // middle spaces
+ i // trailing number
: ""))
.forEach (System.out::println);
}
I did it for fun, here's the code :
import java.util.Scanner;
public class Diamond {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int num = read.nextInt();
read.nextLine();
//TOP
for(int i = 1;i<=num;i++) {
//LEFT
for(int k = i; k<num;k++) {
if ( k % 2 == 0 ) {
System.out.print(" ");
}
else {
System.out.print(" ");
}
}
if(i>1) {
for(int j =1;j<=i;j++) {
if (j==1 || j== i) {
for(int u=0;u<j;u++) {
System.out.print(" ");
}
System.out.print(i);
}
else {
System.out.print(" ");
}
}
System.out.println("");
}
else {
System.out.println(" "+i);
}
}
//BOTTOM
for(int i = num-1;i>0;i--) {
for(int k = i; k<num;k++) {
if ( k % 2 == 0 ) {
System.out.print(" ");
}
else {
System.out.print(" ");
}
}
if(i>1) {
for(int j =1;j<=i;j++) {
if (j==1 || j== i) {
for(int u=0;u<j;u++) {
System.out.print(" ");
}
System.out.print(i);
}
else {
System.out.print(" ");
}
}
System.out.println("");
}
else {
System.out.println(" "+i);
}
}
}
}
And the output :
7
1
2 2
3 3
4 4
5 5
6 6
7 7
6 6
5 5
4 4
3 3
2 2
1
Having seen the other answers, there's a whole load of loops I could've skipped. Just decided to wing it at the end and do it as quick as possible.

Printing Diamonds Java Output not exactly as required

I have developed a code to print a diamond in java. The code prints a diamond using * and "o" and the code is:
System.out.println("Diamond Height: " + DIAMOND_SIZE);
System.out.println("Output for: For Loop");
int noOfRows = DIAMOND_SIZE;
//Getting midRow of the diamond
int midRow = (noOfRows)/2;
//Initializing row with 1
int row = 1;
//Printing upper half of the diamond
for (int i = midRow; i > 0; i--)
{
//Printing i spaces at the beginning of each row
for (int j = 1; j <= i; j++) {
System.out.print(" ");
}
//Printing j *'s at the end of each row
for (int j = 1; j <= row; j++) {
System.out.print("* ");
}
System.out.println();
//Incrementing the row
row++;
}
//Printing lower half of the diamond
for (int i = 0; i <= midRow; i++) {
//Printing i spaces at the beginning of each row
for (int j = 1; j <= i; j++) {
System.out.print(" ");
}
//Printing j *'s at the end of each row
int mid = (row+1) / 2;
for (int j = row; j > 0; j--) {
if(i==0 && j==mid) {
System.out.print("o ");
}
else {
System.out.print("* ");
}
}
System.out.println();
//Decrementing the row
row--;
}
}
The result I get from this is:
Diamond Height: 5
*
* *
* o *
* *
*
Diamond Height: 3
*
* o
*
But Im trying to get the following results:
Diamond Height: 5
*
* * *
* * o * *
* * *
*
Diamond Height: 3
*
* o *
*
What am I doing wrong? I have tried several things but nothing seems to help, Please help.
You can modify your inner loop logic when printing lower half of the diamond.
//Printing j *'s at the end of each row
int mid = (row+1) / 2;
for (int j = row; j > 0; j--)
{
if(i==0 && j==mid) System.out.print("o ");
else System.out.print("* ");
}

Print a Z shape pyramid using * stars

I am trying to write a program that outputs a Z pattern that is n number of * across the top, bottom, and connecting line using for loops.
Example:
Enter a number: 6
******
*
*
*
*
******
This is my current code, it's producing a half pyramid upside down.
import java.util.*;
public class ZShape {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();
for (int x = 0; x <= n; x++) {
for (int y = n; y >= 1; y--) {
if (y > x) {
System.out.print("* ");
}
else
System.out.print(" ");
}
System.out.println();
}
}
}
This is the logic in the following code:
Loop over each row of the output (so from 0 to n excluded so that we have n rows)
Loop over each column of the output (so from 0 to n excluded so that we have n columns)
We need to print a * only when it is the first row (x == 0) or the last row (x == n - 1) or the column is in the opposite diagonal (column == n - 1 - row)
Code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();
for (int row = 0; row < n; row++) {
for (int column = 0; column < n; column++) {
if (row == 0 || row == n - 1 || column == n - 1 - row) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
Sample output for n = 6:
******
*
*
*
*
******
(Note that this output has trailing white-spaces for each row, you did not specify whether they should be included, but it is easy to remove them by adding another check).
How about using three loops instead?
for (int x = 0; x < n; x++) {
System.out.print("*");
}
System.out.println();
for (int x = n-3; x >= 0; x--) {
for (int y = x; y >= 0; y--) {
System.out.print(" ");
}
System.out.println("*");
}
for (int x = 0; x < n; x++) {
System.out.print("*");
}
public class Star {
public static void main(String[] args) {
for (int i = 0; i <=4; i++) {
for (int j = 0; j <=4; j++)
{
if (i==4 || (i+j)==4 || i==0)
{
System.out.print(" * ");
}
else
{
System.out.print(" ");
}
}
System.out.println(" ");
}
}
}
Here is a logic to print Z shape:
when i = 1, then the First line will print only "#"
when i = n, then the Last line will print in same way by "#" only
when i = j, that means it will execute one diagonal line by "#" only
Code:
public static void main(String[] args) {
Scanner scr = new Scanner(System.in);
int n = scr.nextInt();
for (int i = 1; i <= n; i++) {
for(int j = n; j >= 1; j--) {
if (i == 1 || i == n || i == j) {
System.out.print("# ");
}
else {
System.out.print(" ");
}
}
System.out.println();
}
}

How to generate a star Triangle pattern using Java

How to print a star triangle pattern using java. Pattern is something like this
* ====> row 1
* *
* *
* *
* * * * *
it can be n number of rows and from second row onwards there is odd number of white spaces between 2 stars like, 1,3,5, and last row have all the stars each separated by one white space.
Below is the Code I was working on to print the triangle?
public class Triangle
{
public static void main(String[] args)
{
int row = 4;
int space =0;
System.out.println("*");
for (int i=1;i<row;i++)
{
System.out.print("*");
for(space=0;space<i;space = space+i)
{
System.out.print(" ");
}
System.out.print("*");
System.out.println();
}
enter code here
for(int i=0;i<=4;i++)
{
System.out.print("* ");
}
}
}
How do I proceed?
public class Triangle {
public static void DrawWithStars(int dimension)
{
if(dimension < 0)
{
//Assuming that a triangle with dimension = 0 is a dot....
System.out.println("No valid dimension");
}
else
{
//To print the first dimension - 1 rows
for (int i = 0; i < dimension; i++)
{
for (int j = 0; j < dimension - i; j++) {
System.out.print(" ");
}
//Print the dot of the row 1 at the end
if(i != 0)
System.out.print("*");
for (int j = 0; j < 2 * i - 1; j++) {
System.out.print(" ");
}
System.out.println("*");
}
//To print the last row
for (int i = 0; i < dimension; i++)
{
System.out.print("* ");
}
System.out.println("*");
}
}
}
package apple;
public class Triangle
{
public static void main(String...strings){
int midspace = -1;
int row = 4;
String star = "";
for(int y=row-1; y>0; y--){
for(int space = 1;space <= y ; space++){
System.out.print(" ");
}
System.out.print("*");
for(int i = midspace; i>0; i--)
System.out.print(" ");
midspace += 2;
star = (y!=row-1) ? "*":"";
System.out.println(star);
}
for(int y=((row*2)-1); y>0; y--){
System.out.print("*");
}
}
}

Categories

Resources