I am trying to make a pattern (triangle in java) - java

I am trying to make this pattern in java:
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
This is the code which I have written:
package practise;
import java.util.Scanner;
public class PatternsUsingLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int j=1;j<=n;j++) {
for(int k=n;k>=1;k--) {
System.out.print("* ");
}
System.out.println();
}
}
}
please tell me the error

There are many ways to do it also to fix this issue. One of the simplest fixes is to replace the inner loop with the following:
for (int k = (n - j) + 1; k >= 1; k--)
Since you want to print n number of *s in the first line, n - 1 number of *s in the second line and so on, the value of k must be initialized to n when j is 1, n - 1 when j is 2 and so on.
Some of the other ways to do this requirement are as follows:
A.
for (int j = n; j >= 1; j--) {
for (int k = j; k >= 1; k--) {
System.out.print("* ");
}
System.out.println();
}
B.
for (int j = n; j >= 1; j--) {
for (int k = 1; k <= j; k++) {
System.out.print("* ");
}
System.out.println();
}
...and many more

You don't decrease the finish condition in inner loop. This will works:
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int row=0;row<n;row++) {
for (int column = 0; column < n-row; column++) {
System.out.print("* ");
}
System.out.println();
}

The problem is that you haven't tried debugging your code.
To debug your code try printing out the variables that you are using at the beginning of each line to see if they are what you expect. You have (hopefully) thought about the code, and what you think each variable will be on each line, so you've missed something, you have a bug.
For example try this:
package practise;
import java.util.Scanner;
public class PatternsUsingLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int j=1;j<=n;j++) {
System.out.print("j: " + j + " n: " + n);
for(int k=n;k>=1;k--) {
System.out.print("* ");
}
System.out.println();
}
}
}
When you run that you get
j: 1 n: 5* * * * *
j: 2 n: 5* * * * *
j: 3 n: 5* * * * *
j: 4 n: 5* * * * *
j: 5 n: 5* * * * *
Which shows what a couple of the other answers are pointing out, that n doesn't change so the output is always 5 stars.
Now you can figure out the answer. (Hint: start j from 0 and use k=n-j)

Its a very small mistake that you are doing , the first loop is correct but in the inner loop you are printing n stars again (from n to 1).
You need to print (n - i + 1) stars for every loop.
Use this change :
...
...
int n = sc.nextInt();
for(int j=1;j<=n;j++) {
for(int k=n-j+1;k>=1;k--) {
System.out.print("* ");
}
System.out.println();
}
...
...
//... means same code //

Related

Create a Square of stars with an inputed number

I need a code to help me print a square of stars with an Integer input (in this case the number is 5)
the square must be empty on the inside.
for example:
Looking for this output
* * * * *
* *
* *
* *
* * * * *
what I get
* * * *
*
*
*
* * * *
I am missing my right side of the square.
MY code:
System.out.print("Please enter a number: ");
side = input.nextInt();
for (int i = 0; i < side - 1; i++) {
System.out.print("* ");
}
for (int i = 0; i < side; i++) {
System.out.println("*");
}
for (int i = 0; i < side; i++) {
System.out.print("* ");
}
}
input
5
output
* * * *
*
*
*
* * * *
You can do this with a nested for loop.
for (int i = 0; i < side; i++) {
for (int j = 0; j < side; j++) {
if (i == 0 || i == side - 1 || j == 0 || j == side - 1) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
Print a * if it is either first row/column or last row/column; otherwise print two spaces.
It can be done using a single For Loop with a Complexity of O(n)
public static void main(String[] args) {
System.out.print("Please Enter a Number ");
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
if(number >= 3) {
String endPattern = new String(new char[number]).replace("\0", " *");
String midPattern = String.format("%-"+(number-2)*2+"s %s", " *"," *");
for(int i=1; i<= number; i++) {
if(i==1 || i==number) {
System.out.print(endPattern);
}
else {
System.out.print(midPattern);
}
System.out.println();
}
}
}
Output (for input 3)
Please Enter a Number 3
* * *
* *
* * *
output (for input 7)
Please Enter a Number 7
* * * * * * *
* *
* *
* *
* *
* *
* * * * * * *
You need to add an extra star at the end of the middle for loop. This can be done by nested a second for loop of spaces followed by printing the star.
for (int i = 0; i < side; i++) {
System.out.print("*");
for (int j = 0; j < side; j++) {
System.out.print(" ");
}
System.out.println("*");
}

Printing a * pattern

So I have to print the following pattern by accepting a value of n
Input : 7
Output has to be this :
*
**
***
****
*****
******
*******
******
*****
****
***
**
*
code:
public static void printPattern(int n)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
System.out.println("*");
}
System.out.println("\n");
}
for (int a = n-1; a >= 1; a--)
{
for (int b = 1; b <= a; b++)
{
System.out.print("*");
}
System.out.println("\n");
}
}
But for some reason it prints this pattern(say n=8):
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*******
******
*****
****
***
**
*
What is the mistake here?
Use System.out.print instead of System.out.println in the first for loop, the latter one always appends a newline character at the end which is what you are trying to do manually.
And either do System.out.print("\n"); OR System.out.println(""); to add the newline after the inner loop iteration.
System.out.println already adds a line break at the end, therefore System.out.println("\n") adds two line breaks.
The code can be condensed to a single double-for loop. The following routine accepts a single parameter which defines the maximum number of '*' on a single line:
/**
* #param width
* the maximum width of the pattern.
*/
public static void print(int width) {
for (int i = 1; i < 2 * width; ++i) {
for (int j = 0; j < width - Math.abs(width - i); ++j)
System.out.print("*");
System.out.println();
}
}
public static void main(String[] args) {
print(4);
}
Output:
*
**
***
****
***
**
*
first for loop should be like this,
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.print("\n");
}
System.out.println();
always move the cursor to a new line
in your code when we use System.out.println("\n"); this will move cursor to 2 lines
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
for (int a = n - 1; a >= 1; a--) {
for (int b = 1; b <= a; b++) {
System.out.print("*");
}
System.out.println();
}
By changing println to print you won't go to another line after each * and remove the \n to not skip 2 lines because println it's already there

Print a diamond shape with Java

I want to print a grid shape on the output console in Eclipse.
Basically I took an integer from user that is the number of stars in a single border of the grid.
Here the code I have up to now:
public class PrintDiamond {
public static void main(String[] args) {
System.out.print("Enter the number: ");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
num--;
for (int i = num; i > 0; --i) {
//Insert spaces in order to center the diamond
for (int n = 0; n < i; ++n) {
System.out.print(" ");
}
System.out.print(" *");
for (int n = i; n < num; ++n) {
System.out.print(" + ");
System.out.print(" ");
}//Ending bracket of nested for-loop
System.out.println();
}//Ending bracket of for loop
//Print out a diamond shape based on user input
for (int i = 0; i <= num; ++i) {//<= to print the last asterisk
//Insert spaces in order to center the diamond
for (int n = 0; n < i; ++n) {
System.out.print(" ");
}
System.out.print(" *");
for (int n = i; n < num; ++n) {
System.out.print(" + ");
System.out.print(" ");
}//Ending bracket of nested for-loop
System.out.println();
}//Ending bracket of for loop
}
}
and the output is (for int. 6):
*
* +
* + +
* + + +
* + + + +
* + + + + +
* + + + +
* + + +
* + +
* +
*
Here is the code:
public static void main(String[] args) {
System.out.print("Enter the number: ");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
final char[][] diamond = makeDiamond(num);
for (int i = 0; i < diamond.length; i++) {
for (int j = 0; j < diamond[i].length; j++) {
System.out.print(diamond[i][j]);
}
System.out.println();
}
}
public static char[][] makeDiamond(int n) {
int width = 1 + 4 * (n - 1);
int height = 1 + 2 * (n - 1);
char[][] out = new char[height][width];
int x0 = 2 * (n - 1);
int y0 = n - 1;
for (int i = 0; i < width; i += 2) {
// Top borders
int y1 = Math.abs(y0 - i / 2);
out[y1][i] = '*';
// Bottom borders
int y2 = height - Math.abs(i / 2 - y0) - 1;
out[y2][i] = '*';
if ((x0 - i) % 4 == 0) {
// Plus signs
for (int j = y1 + 1; j < y2; j++) {
out[j][i] = '+';
}
}
}
return out;
}
Some hints for your solution:
Create a method for printing a "diamond row" for a given row width and a given total width of the diamond.
Create a tool method for printing a given number of spaces.
Your main method should have two simple loops: One for the upper, one for the lower half.
The magic is in the method of printing a single diamond row for the given two parameters w and n.
This is always a good approach - reduce your complex problem to a problem with lesser complexity - in this case, by creating methods and using these e.g. in loops.
In your method for printing a single diamond row, you will need to check if you are in an "odd" or "even" row.
Ok, this looks like a school asignment, so I won't write any code.
First you need to understand and write, in pseudo-code or just plain English, what you want to do:
Instructions on how to draw the grid.
How many lines should I print?
How long is each line?
How do I know if I have to print a + or not?
General steps of your program.
Read size of the grid, N.
If N < 1, ask again (or exit program).
If N = 1 or greater, print the grid.
Detailed sub-steps of your program.
Print the grid
Loop for number of lines.
Create empty array/buffer/list/string with correct length for current line.
...
Because right now, it seems like you haven't figured out any of that. And if that's the case, then your problem has nothing to do with Java but rather with basic programming knowledge, which you won't get if we just code the algorith for you.
Two nested for loops from -n to n and one if else statement. The zero point is in the center of a diamond, and the boundary is obtained when:
Math.abs(i) + Math.abs(j) == n
Try it online!
public static void main(String[] args) {
printDiamond(0);
printDiamond(2);
printDiamond(5);
}
static void printDiamond(int n) {
System.out.println("n=" + n);
for (int i = -n; i <= n; i++) {
for (int j = -n; j <= n; j++)
if (Math.abs(i) + Math.abs(j) == n)
System.out.print("* ");
else if (Math.abs(i) + Math.abs(j) < n && j % 2 == 0)
System.out.print("+ ");
else
System.out.print(" ");
System.out.println();
}
}
Output (combined):
n=0
n=2
n=5
*
* * + * * + * * + * *
* * + * * + * * + + + * * + + + * * + + + + + * * + + + * * + + + * * + * * + * *
See also: Print an ASCII diamond of asterisks

Pattern using looping

I have to make a loop that will read the user's input (let's say his input is 5) so the output should be as the following:-
*
**
***
****
*****
****
***
**
*
int x;
//input size of triangle from 1-20
Scanner scanner = new Scanner (System.in);
System.out.println("Enter size of triangle from 1 to 20: ");
x = scanner.nextInt ();
for( int i = 0; i <= x; i++){
for(int j=0; j < i; j++){
System.out.print( " *");
}
System.out.println(" ");
I just don't know how to finish it by decreasing the pattern so I can form a full triangle.
example using ternary operator .increase j if x grater than i decrease otherwise
int x = 5, j=0;
for (int i = 0; i <= x*2; i++) {
j= (x>i)? ++j:--j; // u can use if else also
for (int y = 0; y < j; y++) {
System.out.print(" *");
}
System.out.println("");
}
output>>
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
The following code prints the triangle, assuming the user enters 10
for (int i = 0; i < 10; i++){
for (int j = 0;j < i;j++ )
System.out.print('x');
System.out.println();
}
for (int i = 10; i > 0; i--){
for (int j = 0; j < i;j++)
System.out.print('x');
System.out.println();
}
In your code, you exclude the second for loop in which i is decremented.
import java.util.Scanner;
public class Triangle {
public static void printLine(int n) {
for(int i = 0; i < n; i++) System.out.print("*");
System.out.print("\n");
}
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.println("Enter size of triangle");
int x = scanner.nextInt ();
for(int i = 0; i < x; i++) {
printLine(i);
}
for(int i = x; i > 0; i--) {
printLine(i);
}
}
}
The output :
Enter size of triangle
5
*
**
***
****
*****
****
***
**
*

Making an ASCII rhombus with loops

I got a problem to create a rhombus, my code here:
package random;
public class asd {
public static void main(String args[]) {
for (int j = 1; j <= 4; j++) {
for (int kong = 4 - j; kong >= 1; kong--) {
System.out.print(" ");
}
for (int xing = 1; xing <= 2 * j - 1; xing++) {
System.out.print("*");
}
System.out.println();
}
for (int a = 1; a <= 3; a++) {
for (int b = 1; b <= a; b++) {
System.out.print(" ");
}
for (int c = 5; c >= 1; c -= 2) { // <==== here
System.out.print("*");
}
System.out.println();
}
}
}
However, the output is:
*
***
*****
*******
***
***
***
I think the problem is in the code which I highlighted.
java-11
By using String#repeat, introduced as part of Java-11, you can do it with a single loop.
public class Main {
public static void main(String[] args) {
int size = 9;
int midRowNum = size / 2 + 1;
for (int i = 1 - midRowNum; i < midRowNum; i++) {
System.out.println(" ".repeat(Math.abs(i)) + "*".repeat((midRowNum - Math.abs(i)) * 2 - 1));
}
}
}
Output:
*
***
*****
*******
*********
*******
*****
***
*
By increasing the amount of space by one character, you can also print a variant of the shape:
public class Main {
public static void main(String[] args) {
int size = 9;
int midRowNum = size / 2 + 1;
for (int i = 1 - midRowNum; i < midRowNum; i++) {
System.out.println(" ".repeat(Math.abs(i)) + "* ".repeat((midRowNum - Math.abs(i)) * 2 - 1));
}
}
}
Output:
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
You are right in indicating the possible problematic line. Surprised that you did it right in first half:
for (int c = 5; c >= 2 * a - 1; c -= 1) { // <==== here
System.out.print("*");
Using Math.abs will make it a lot easier:
import java.util.Scanner;
public class MakeDiamond {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Let's Creat Diamonds");
System.out.println("If number increases Diamonds gets bigger. " +
"Please input number lager than 1 : ");
int user_input = sc.nextInt(); //gets user's input
System.out.println("");
int x = user_input;
int front_space = -5;
for (int i = 0; i < 2 * user_input + 1; i++) {
for (int a = front_space; a < Math.abs(i - user_input); a++) {
System.out.print(" ");
}
if (i < user_input + 1) {
for (int b = 0; b < 2 * i + 1; b++) {
System.out.print("* ");
}
} else if (i > user_input) {
for (int c = 0; c < 2 * x - 1; c++) {
System.out.print("* ");
}
x--;
}
System.out.print('\n');
}
System.out.println("\nRun Again? 1 = Run, 2 = Exit : ");
int restart = sc.nextInt();
System.out.println("");
if (restart == 2) {
System.out.println("Exit the Program.");
System.exit(0);
sc.close();
}
}
}
}
You can simplify your code by using two nested for loops and one if else statement.
int n = 4;
for (int i = -n; i <= n; i++) {
for (int j = -n; j <= n; j++)
if (Math.abs(i) + Math.abs(j) <= n)
System.out.print("*");
else
System.out.print(" ");
System.out.println();
}
Output:
*
***
*****
*******
*********
*******
*****
***
*
See also: Output an ASCII diamond shape using loops

Categories

Resources