Printing an ASCII Diamond: Bottom half broken? - java

I am attempting to print a diamond using a user inputted width of 7 that is supposed to look like this:
*
* *
* *
* *
* *
* *
*
BUT, unfortunately my diamond is messed up on the bottom and it looks like this:
*
* *
* *
* *
* *
*
Here's my code:
public static void main (String[] args)
{
int width = 0;
System.out.println("What is the width?");
Scanner keyboard = new Scanner (System.in);
width = keyboard.nextInt();
//Print top half of the diamond
for (int i = 0; i < width; i += 2) {
if (i == 0) {
for (int j = 0; j < (width / 2) + 1; j++)
System.out.print(' ');
System.out.print('*');
} else {
for (int j = 0; j < width - i; j += 2) {
System.out.print(' ');
}
System.out.print('*');
for (int j = 0; j < i - 1; j++) {
System.out.print(' ');
}
System.out.print('*');
}
System.out.print('\n');
}
//Print bottom half of the diamond
for (int i = 0; i < 3; i+=2) {
if (i == 2) {
for (int j = 0; j < (width / 2) + 1; j++)
System.out.print(' ');
System.out.print('*');
} else {
for (int j = 0; j <= i + 2; j += 2) {
System.out.print(' ');
} System.out.print ('*');
for (int j = 0; j < (width / 2) - i; j++) {
System.out.print(' ');
} System.out.print('*');
}
System.out.print('\n');
}
}
I am not totally sure how to fix the bottom part of it, that is what I have been trying to figure out! These nested for loops are tricky

For simple fix, change bottom loop variable i from 3 to 5, and line after that i from 2 to 4.
//Print bottom half of the diamond
for (int i = 0; i < 5; i+=2) {
if (i == 4) {
for (int j = 0; j < (width / 2) + 1; j++)
System.out.print(' ');
System.out.print('*');
} else {
for (int j = 0; j <= i + 2; j += 2) {
System.out.print(' ');
} System.out.print ('*');
for (int j = 0; j < (width / 2) - i; j++) {
System.out.print(' ');
} System.out.print('*');
}
System.out.print('\n');
}

Try changing the 3 in bottom half for loop to 4. It seems as you lack one row. That might do it. Can't promise I'm new here and just trying to help! :)

Related

Trying to print out a diamond made of stars, and it cannot print even numbers

for one of my assignments I am required to print out stars in the shape of a diamond. When trying to print odd numbers, everything works out fine. However, when trying to print even numbered diamonds, the spacing in the middle lines is off, and a diamond is missing. Could someone please point out what I am doing wrong, and provide a possible fix?
public void printStarsDiamond(int d)
{
for (int i = 1; i < d; i = i + 2)
{
for (int j = 0; j < (d - i) / 2; j++)
{
System.out.print(" ");
}
for (int k = 0; k < i; k++)
{
System.out.print("*");
}
System.out.println();
}
for (int i = d; i > 0; i = i - 2)
{
for (int j = 0; j < (d - i) / 2; j++)
{
System.out.print(" ");
}
for (int k = 1; k <= i; k++)
{
System.out.print("*");
}
System.out.println();
}
Desired result, if the user enters 6 (d = 6)
If you notice your code, the second for loop is starting from
i = d in
for (int i = d; i > 0; i = i - 2)
but your first loop is not ending at d, you are doing i < d there which will stop before d, so it will go from 1 to 5 if your d value is 6.
Simply change your second main for loop to start from d-1, here is the code
public void printStarsDiamond(int d)
{
for (int i = 1; i < d; i = i + 2)
{
for (int j = 0; j < (d - i) / 2; j++)
{
System.out.print(" ");
}
for (int k = 0; k < i; k++)
{
System.out.print("*");
}
System.out.println();
}
for (int i = d-1; i > 0; i = i - 2)
{
for (int j = 0; j < (d - i) / 2; j++)
{
System.out.print(" ");
}
for (int k = 1; k <= i; k++)
{
System.out.print("*");
}
System.out.println();
}
The code below will print a diamond pattern using a single loop:
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++;
}
}
(This code is taken from an article published on my website: https://programtown.com/how-to-print-diamond-pattern-using-single-for-loop-in-java/.)

Using for loops to create an upside-down triangle [duplicate]

This question already has answers here:
Creating a triangle with for loops
(13 answers)
Closed 8 years ago.
Im a java student, and i'm have quite the hard time, trying to use for loops to create an upside down triangle.
This is what my code looks like now, a straight forward triangle. How can i make another one just like it, but upside down?
for (int i=1; i<20; i += 2)
{
for (int k=10; k < (0 - i / 2); k++)
{
System.out.print(" ");
}
for (int j=0; j<i; j++)
{
System.out.print("*");
}
System.out.println("");
}
Is that tricky?
Just change
for (int i=1; i<20; i += 2)
To
for (int i = 19; i >0; i -= 2)
Code.
for (int i = 19; i > 0; i -= 2) {
for (int k = 10; k < (0 - i / 2); k++) {
System.out.print(" ");
}
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println("");
}
Out put:
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*
int c = 2*lines;
for (int i = lines-1; i>=0; i--)
{
for (int j = i; j < lines; j++)
{
System.out.print(" ");
}
for (int k = 1; k <= c; k++)
{
if (k % 2 == 0)
{
System.out.print(" ");
}
else
{
System.out.print(symbol);
}
}
System.out.print("\n");
c -= 2;
}
All you have to do is to change your 3rd for loop
for (int j=0; j<i; j++)
{
System.out.print("*");
}
In your code, you print 1 star, 3 stars, 5 stars and so on... (i stars actually)
To make it upside down, start the j at the max value and decrement it so you print n - i stars
for (int j = 20 - i; j > 0; j--)
{
System.out.print("*");
}
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
for (int i = 1; i < 20; i += 2) {
for (int k = 10; k < (0 - i / 2); k++) {
sb.append(" ");
}
for (int j = 0; j < i; j++) {
sb.append("*");
}
sb.append("\n");
}
System.out.println(sb.reverse());
}
However you are probably supposed to learn something about loops and the algorithm.

Reversing Java For Loop

I have this code, which I am trying to print the following shape out...
****
* *
**
*
Current Code:
System.out.print("\nEnter number of rows: ");
rows = kybd.nextInt();
for (int i = 0; i < rows; i++) {
System.out.print("*");
}
for (int i = 0; i < rows; i++) {
for (int j = 1; j <= i; j++) {
if (j == 1 || j == rows - 1 || j == i) {
System.out.print("*");
} else {
System.out.print("0");
}
}
System.out.println();
}
For some reason, it prints out like this:
****
*
**
* *
Any idea how to reverse the second for loop, so it prints the other way?
I feel you should change your i loop
for (int i = rows - 1; i > 0 ; i--)
Try this:
Scanner kybd = new Scanner(System.in);
System.out.print("\nEnter number of rows: ");
int rows = kybd.nextInt();
if (rows > 1) {
for (int i = 0; i < rows; i++)
System.out.print("*");
System.out.println();
for (int i = rows - 1; i > 1; i--) {
System.out.print("*");
for (int j = 2; j < i; j++)
System.out.print(" ");
System.out.println("*");
}
}
System.out.println("*");
Sample output:
Enter number of rows: 6
******
* *
* *
* *
**
*
Notice, that you are printing out the first line of asterisk in a separate cycle, not inside the main one. If you want to follow this road, you need to put the first cycle behind the second one.
for (int i = 0; i < rows; i++) {
for (int j = 1; j <= i; j++) {
if ((j == 1) || (j == (rows - 1)) || (j == i)) {
System.out.print("*");
} else {
System.out.print("0");
}
}
System.out.println();
}
for (int i = 0; i < rows; i++) {
System.out.print("*");
}

Printing a triangle in Java

I'm practicing basic coding exercises and trying to print the following triangle in Java:
*
***
*****
***
*
The following code gives me the results but I feel like there must be a much more elegant solution
for (int i = 1; i <= 5; i++) {
if (i % 2 == 1) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
}
for (int i = 3; i > 0; i--) {
if (i % 2 == 1) {
for (int j = 1; j < i + 1; j++) {
System.out.print("*");
}
System.out.println("");
}
}
Can anyone provide some insight into how to make this work in a better way?
Ok, here's some more code that produces the correct result that uses just the two for loops, but it looks even uglier:
for (int i = 1; i <= 10; i += 2) {
if (i <= 5) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
else if(i > 5 && i < 8){
for(int j = i/2; j > 0; j--){
System.out.print("*");
}
System.out.println("");
}
else{
for(int j = 1; j > 0; j--){
System.out.print("*");
}
System.out.println("");
}
}
First, you are skipping each 2nd iteration of the loop because you want to increase two steps at once. You can do this by changing the "i++" in your loop to "i += 2" and "i--" to "i -= 2", that will have the same effect and allows you to remove the if inside both loops.
Another improvement would be using a single outer loop and figuring out whether the inner loop should be increasing or decreasing the amount of asterisks. Maybe you can come up with an equation that gives you the amount of asterisks based on the value of i? (I didn't want to solve it completely so you have some exercise left, just comment if you want a full solution)
Updated with a solution that might be considered elegant as you can change the height of the triangle and there is no repetition:
int height = 5;
for (int i = 1; i <= 2 * height; i += 2) {
int numAsterisks;
if (i <= height) {
numAsterisks = i;
} else {
numAsterisks = 2 * height - i;
}
for (int j = 0; j < numAsterisks; j++) {
System.out.print("*");
}
System.out.println();
}
What about the following?
public void printTriangle(int size) {
int half = size / 2;
for (int i = 0; i < size; i++) {
int stars = 1 + 2 * (i <= half ? i : size - 1 - i);
char[] a = new char[stars];
Arrays.fill(a, '*');
System.out.println(new String(a));
}
}
Or just a bit more optimized:
public void printTriangle(int size) {
int half = size / 2;
char[] a = new char[size];
Arrays.fill(a, '*');
for (int i = 0; i < size; i++) {
int stars = 1 + 2 * (i <= half ? i : size - 1 - i);
System.out.println(new String(a, 0, stars));
}
}
for(int i = 0; i < 7; i++) {
for(int j = 0; j < i; j++) {
print("*");
}
print("\n");
}
This can be another solution to print a regular right triangle...
Here's a different way of looking at the problem. By using an integer array, I can solve lots of shape drawing problems by changing the values in the array.
When solving more difficult problems, you would use model classes instead of simple integers. The idea, however, is the same.
Here's the output.
*
***
*****
***
*
And here's the code:
public class Triangle {
public static void main(String[] args) {
int[] heights = {1, 3, 5, 3, 1};
for (int i = 0; i < heights.length; i++) {
for (int j = 0; j < heights[i]; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}
How about...
int width = 5;
for (int i = 1; i <= width; i+=2){
System.out.println(String.format("%"+i+"s", "").replaceAll(" ", "*"));
}
for (int i = width-2; i > 0; i-=2){
System.out.println(String.format("%"+i+"s", "").replaceAll(" ", "*"));
}
Or, even better yet...
int width = 7;
double half = width / 2
for (int i = 0; i < width; i++){
System.out.println(String.format("%"+((i < half ? i : (width-i-1))*2+1)+"s", "").replaceAll(" ", "*"));
}
Gives
*
***
*****
***
*

Print an ASCII diamond of asterisks

My program that prints out a diamond like this:
...............*
..........* * *
.....* * * * *
* * * * * * *
.....* * * * *
..........* * *
...............*
But it only works if the parameter or each side of the diamond is 4. For example if I input 6, the spacing on the bottom triangle is wrong and I been trying to figure it out.
The bottom triangle doesn't change when the parameter is changed, only the top one does. It only works for input 4.
public static void printMoreStars(int n) {
int rowsPrime = 0;
for (int i = n + 1; i > 0; i--) {
for (int j = 0; j < (2 * i) - 1; j++) {
System.out.print(" ");
}
for (int d = 0; d < (2 * rowsPrime) - 1; d++) {
System.out.print("*" + " ");
}
System.out.println(); //new line character
rowsPrime += 1;
System.out.println(" ");
}
//bottom triangle
for (int i = 1; i < n + 1; i++) {
for (int j = 0; j < (2 * i) + 1; j++) {
System.out.print(" ");
}
for (int d = 0; d < rowsPrime; d++) {
System.out.print("*" + " ");
}
System.out.println(); //new line character
rowsPrime -= 2;
System.out.println(" ");
}
}
You made two mistakes when using rowPrimes. See my annotations below:
public class Stars {
public static void main(String[] args) {
printMoreStars(Integer.parseInt(args[0]));
}
public static void printMoreStars(int n) {
int rowsPrime = 0;
for (int i = n + 1; i > 0; i--) {
for (int j = 0; j < (2 * i) - 1; j++) {
System.out.print(" ");
}
for (int d = 0; d < (2 * rowsPrime) - 1; d++) {
System.out.print("*" + " ");
}
System.out.println(); //new line character
rowsPrime += 1;
System.out.println(" ");
}
rowsPrime -= 2; // <- middle line is already printed, so skip that
//bottom triangle
for (int i = 1; i < n + 1; i++) {
for (int j = 0; j < (2 * i) + 1; j++) {
System.out.print(" ");
}
for (int d = 0; d < (2 * rowsPrime) - 1; d++) { // <- changed condition to be the same as above
System.out.print("*" + " ");
}
System.out.println(); //new line character
rowsPrime--; // <- you have to decrease rowPrime by one.
System.out.println(" ");
}
}
}
To print a rhombus with dots on the left, you can use this code.
Try it online!
public static void main(String[] args) {
printRhombus(3);
}
public static void printRhombus(int n) {
for (int i = -n; i <= n; i++) {
// last element in the row
int last = n - Math.abs(i);
for (int j = -n; j <= last; j++)
if (Math.abs(i) + Math.abs(j) <= n)
System.out.print("*" + (j < last ? " " : ""));
else
System.out.print(".....");
System.out.println();
}
}
Output:
...............*
..........* * *
.....* * * * *
* * * * * * *
.....* * * * *
..........* * *
...............*
See also: Print a diamond shape with Java
Check This:
import java.io.*;
import java.lang.*;
import java.util.*;
class DiamondPattern {
static public int ReadInteger() {
try {
String inpString = "";
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
String s = reader.readLine();
return Integer.parseInt(s);
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
public static void main(String[] args) {
System.out.println("Program for displaying pattern of *.");
System.out.print("Enter the maximum number of *: ");
int n = ReadInteger();
System.out.println("\nHere is the Diamond of Stars\n");
for (int i = 1; i <= n; i++) {
for (int j = 0; j < (n - i); j++)
System.out.print(" ");
for (int j = 1; j <= i; j++)
System.out.print("*");
for (int k = 1; k < i; k++)
System.out.print("*");
System.out.println();
}
for (int i = n - 1; i >= 1; i--) {
for (int j = 0; j < (n - i); j++)
System.out.print(" ");
for (int j = 1; j <= i; j++)
System.out.print("*");
for (int k = 1; k < i; k++)
System.out.print("*");
System.out.println();
}
System.out.println();
}
}

Categories