This question already has answers here:
Java algorithm to make a straight pyramid [closed]
(4 answers)
Closed 3 years ago.
I need to write a code for pyramid pattern with asterisks. yeah, it sounds like the codes on everywhere. but, i need to make a pyramid with a number of asterisks, not a number of rows.
for example, if user gave 9, then need to print a pyramid until the asterisks runs out. It should be center pyramids.
I've tried with the number of rows. but i have no idea how to print with the number of asterisks. while loop could be my answer, but i'm not sure..
public static void main(String args[]) {
int n = 5; // number of rows
for (int i = 0; i < n; i++)
{
for (int j = n - i; j > 1; j--)
{
System.out.print(" ");
}
for (int j = 0; j <= i; j++)
{
System.out.print("* ");
}
System.out.println();
}
}
the result should be like this, but without space between asterisks..
*
* *
* * *
* * * *
* * * * *
my output is showing exactly same thing, but i'm using a number of rows, not number of asterisks.
Not an optimal solution, but you set a maximum number of rows with n=100.
Then you define your asterix number to break out of nested loop. ctr is the total number of asterix.
It goes until desired number asterix reached, checking ctr value.
int n = 100;
int ctr = 0;
int asterix = 5;
for (int i = 0; i < n; i++)
{
for (int j = n - i; j > 1; j--)
{
System.out.print(" ");
}
for (int j = 0; j <= i; j++)
{
ctr++;
System.out.print("* ");
if(ctr == asterix ){
i=j=n;
}
}
System.out.println();
}
}
Based on #Hans Kesting's idea.
public static void main(String args[]) {
int n = 5; // number of asterisks
int max = (int)((1+Math.sqrt(1+8*n))/2);
for (int i = 0; i < n; i++)
{
for (int j = max - i; j > 1; j--)
{
System.out.print(" ");
}
for (int j = 0; j <= i; j++)
{
System.out.print("* ");
--n;
}
System.out.println();
}
}
Related
This question already has answers here:
Creating a triangle with for loops
(13 answers)
Closed 3 years ago.
I started learning java, and that's my question :
How to write to the right side of the triangle?
import java.util.Scanner;
public class Triangle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("please enter your siz triangle :");
int lines = scanner.nextInt();
for (int i = 0; i <= lines; i++) {
for (int j = 1; j < i; j++) {
System.out.println("*");
}
}
scanner.close();
}
}
for 5 i get:
*
*
*
*
*
You can do it like this, use two loops first one to print the number of spaces and then second to print the number of stars based on the number of rows inputted by user. This prints the complete triangle :
Scanner scanner = new Scanner(System.in);
System.out.println("please enter your siz triangle :");
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
for (int j = n - i; j > 1; j--) {
// printing spaces
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
// printing stars
System.out.print("* ");
}
System.out.println();
}
scanner.close();
You are almost there, you need to know how to print. And small correction in for loop indexes. Starting j with 1 will lose one row. I set it to 0 and starting i with 1
for (int i = 1; i <= lines; i++) {
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
Input:
3
Output:
*
**
***
I have recently started java, so I unfortunately am terrible at this. I have an question about a for loop question that was asked in my class today, but I can't figure out a part of it.
We were supposed to print out:
__1__
_333_
55555
with only for loops.
I have started the code but can't figure out what to do to print out the numbers, though I figured out the spaces.
public class Question{
public static void main(String [] args){
for(int j=1; j<=3;j++){
for(int i=1; i<=3-j; i++){
System.out.print(" ");
}
for(int k=?; k<=?; k??){
System.out.print(???);
}
for(int m=1; m<=3-j; m++){
System.out.print(" ");
}
System.out.println();
}
The question mark are the place where I don't know what goes in there.
Thanks.
You can do something like this,
class Main {
public static void main(String[] args) {
int i, j, k;
for (i = 1; i <= 3; i++) {
for (j = 2; j >= i; j--) {
System.out.print("_");
}
for (k = 1; k <= (2 * i - 1); k++) {
System.out.print(i * 2 - 1);
}
for (j = 2; j >= i; j--) {
System.out.print("_");
}
System.out.println();
}
}
}
The first for loop will print the _ before the number, second one will print the number and 3rd one will print the _ after the number
The values are changing by two each time j increments, that leads to the formula 1 + (2 * (j - 1)) which is how you can finish your loops. Like,
for (int j = 1; j <= 3; j++) {
for (int i = 1; i <= 3 - j; i++) {
System.out.print(" ");
}
int n = 1 + (2 * (j - 1));
for (int k = 1; k <= n; k++) {
System.out.print(n);
}
for (int m = 1; m <= 3 - j; m++) {
System.out.print(" ");
}
System.out.println();
}
Outputs
1
333
55555
Thanks everyone for helping. I figured out the answer.
public class Welcome {
public static void main(String [] args){
for(int j=1; j<=3;j++){
for(int i=1; i<=3-j; i++){
System.out.print(" ");
}
for(int k=1; k<=(2*j-1); k++){
System.out.print(2*j-1);
}
for(int m=1; m<=3-j; m++){
System.out.print(" ");
}
System.out.println();
}
}
}
This can also be achieved as below
public class ForLoopPrinter {
public static void main(String[] args) {
int number = 1;
int row = 3;
int column = 5;
char space = '_';
for(int i = 1; i <= row; i++){
for(int j = 1; j <=column;j++){
int offset = (column - number)/2;
if( j <= offset ||
j > (number + offset)){
System.out.print(space);
}else{
System.out.print(number);
}
}
System.out.println();
number += 2;
}
}
}
Here number of For loops are limited to 2 (one for row and one for column).
Logic goes like this -
offset provides you number of spaces to be printed at both sides of number.
first if condition checks if j (position) is below or above offset and if true it prints underscore and if false it prints number
I know that right answer has been given for this question and it will work like charm. I just tried to optimise code by reducing number of For Loops in answers provided before. Reduction of For loop will improve performance.
Apart from reduction of For loops, this code has following advantage
- This code is more scalable. Just change row, column values (e.g. 5,9) or space char to '*' and check output. You can play with it.
I would suggest you to go with answer given by #Sand to understand For loop and then check this answer to understand how you can optimise it.
Here is what I am trying to create:
*
**
***
****
*********
****
***
**
*
Here is what i have created:
*
**
***
****
**********
****
***
**
*
Here is my code:
for(int i = 1; i <= 5; i++){
for(int j = 1; j<=i; j++){
System.out.print("*");
}
System.out.println();
if(i == 4){
for(int f = 0; f < 5; f++){
System.out.print("*");
}
}
}
for(int i = 1; i <= 5; i++){
for(int j = 4; j>=i; j--){
System.out.print("*");
}
System.out.println();
}
I dont know how to indent the tail part, please dont give me the answer, just tell me where the problem is and I will try to do it. Thank you!
Given the shape you have provided, and assuming it's going to be output in a monospace font, we can draw it on a grid.
Splitting it visually into 2 sections, we can see that there are 2 main modes.
The tail (green), and the head (red).
There's also a second mode. where the number of stars in the head increase and decrease.
The size of the tail could potentially vary, as could the size of the head, and it would still be a shape we recognise as an arrow.
When outputting text, the easiest iteration order is generally left to right, up to down, unless dealing with right to left languages, or vertical reading, I'm going to assume western culture for the output, as that is what's been popularised in programming output streams.
So, the question is, how best to build up the strings required for output.
Given the format that the output is going to be on a stream,
width is going to be your outside loop, and tail/length your inside loop.
The code you provided uses 10 for width, by splitting it into 2 groups of 5, with the second one being offset by one.
for(int i = 1; i <= 5; i++){
for(int j = 1; j<=i; j++){
System.out.print("*");
}
System.out.println();
if(i == 4){
for(int f = 0; f < 5; f++){
System.out.print("*");
}
}
}
for(int i = 1; i <= 5; i++){
for(int j = 4; j>=i; j--){
System.out.print("*");
}
System.out.println();
}
so translating your code back to the drawings, you loop over width, and on the last iteration output the line of stars for the tail.
What you need to do, is output a space on all other lines.
There are a variety of ways to do so, you could output the character, or use one of the fixed width formatting functions using printf.
But given your current code, the minimal difference will be to output a space character, when the width iteration for the increasing mode is not 4, and for the loop of width - 1.
Looking at your end result, your tail is being printed after your head. That needs to move earlier.
Your tail is too long, need to offset that by 1.
And you need to insert pink and brown sections by printing spaces, the same amount of times as you output the tail, whenever you do not output the tail.
You should add another inner for-loop that prints " " before the for-loop that prints "*".
You can use printf method to tell Java print in specific format. For example, you need 5 spaces prefixed then print your text:
System.out.printf("%5s","hello");
To get your desired output, try the below code. Note: There may be better solutions.
for (int i = 1; i <= 5; i++) {
if (i != 5) // middle line should not be prefix with spaces
// empty 5 spaces before starting the loop
System.out.printf("%5s", "");
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
if (i == 4) {
for (int f = 0; f < 5; f++) {
System.out.print("*");
}
}
}
for (int i = 1; i <= 5; i++) {
// print 5 space before
System.out.printf("%5s", ""); // <== note the printf here with empty string
for (int j = 4; j >= i; j--) {
System.out.print("*");
}
System.out.println();
}
Here's a method you can use to print the arrow:
private static void printArrow (final int min, final int max, final int tip)
{
final int numSpaces = tip - max - 1;
// print the top
for (int i = min; i <= max; i++)
{
for (int j = 0; j < numSpaces; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.println();
}
// print the tip
for (int i = 0; i < tip; i++)
{
System.out.print("*");
}
System.out.println();
// print the bottom
for (int i = max; i >= min; i--)
{
for (int j = 0; j < numSpaces; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.println();
}
}
Call it from main with:
public static void main(String[] args)
{
// this will print the arrow in your question
printArrow(1, 4, 9);
}
Another Example:
printArrow(1, 10, 19);
Outputs:
*
**
***
****
*****
******
*******
********
*********
**********
*******************
**********
*********
********
*******
******
*****
****
***
**
*
Here is my answer. You just need to first insert the space and then print * until you reach the middle line. If you want to make it dynamic, just replace the boundary value for k dynamically the same as the boundary for the f:
public static void main(String[] args) {
int k = 1;
int m = 0;
for (int i = 1; i <= 5; i++) {
m = i - 1;
while (k != 6 && m != 4) {
System.out.print(" ");
k++;
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
if (i == 4) {
for (int f = 0; f < 5; f++) {
System.out.print("*");
}
}
k = 1;
}
k = 1;
for (int i = 1; i <= 5; i++) {
while (k != 6) {
System.out.print(" ");
k++;
}
for (int j = 4; j >= i; j--) {
System.out.print("*");
}
System.out.println();
k = 1;
}
}
EDIT
I realized the output is one* behind. So just need to change the boundary value of k from 5 to 6 (from the value of boundary for f to the value of boundary for f+1)
The output looks like this:
for (int i = 1; i <= 5; i++) {
if (i!=5) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
if (i == 4) {
for (int f = 0; f < 5; f++) {
System.out.print("*");
}
}
}
for (int i = 1; i <= 5; i++) {
System.out.print(" ");
for (int j = 4; j >= i; j--) {
System.out.print("*");
}
System.out.println();
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I really don't get why all the downvotes:
I posted my own tentative for it.
It's well explained what was needed
I researched the topic extensively, I just found other types of things that for a beginner like me (I started Java a few weeks ago) are quite different.
The only problem I see here, to be honest, is people downvoting a question because they didn't read the thread, or because they are judging someone as lazy without really knowing what is going on.
I'm learning Java.
I'm trying the thing below, you input a number and it creates a triangle with asterisks. I have it pretty much figured out except that my second loop is not giving me what I think it should be giving (going from a given range to a limit, it's incrementing instead of the opposite, and it's driving me insane).
I can't wrap my mind around why isn't it working as supposed. I just need a fresh pair of eyes on it (and suggestions on how to learn to see those things by myself).
The output for 3 at this moment is:
*
**
***
*
**
instead of
*
**
***
**
*
Below is my code for it, with the explanation with what I was trying to do:
/*
Write a program that asks the user to enter the size of a triangle (an integer
from 1 to 50). Display the triangle by writing lines of asterisks. The first
line will have one asterisk, the next two, and so on, with each line having one
more asterisk than the previous line, up to the number entered by the user.
On the next line write one fewr asterisk and continue by decreasing the number
of asterisk by 1 for each successive line until only one asterisk is displayed.
Hint: use nested for loops; the outside loop controls the number of lines to
write, and the inside loop controls the number of asterisks to display on a line)
For example, if the user enters 3, the output would be:
*
**
***
**
*
*/
import java.util.Scanner;
public class Triangles
{
public static void main (String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter the number of your triangle (1 to 50):");
int userInput = kb.nextInt();
int minus = userInput -1;
int lineNumber = userInput + minus;
int half = (lineNumber / 2) + 1;
for(int i = 1; i <= half; i++)
{
System.out.println("");
for (int j = 1; j <= i; j++)
{
System.out.print("*");
}
}
for (int i = minus; i >= 1; i--)
{
System.out.println("");
for (int j = minus; j >= i; j--)
{
System.out.print("*");
}
}
}
}
Just change the inner loop:
for (int i = minus; i >= 1; i--)
{
System.out.println("");
for (int j = 1; j <= i; j++)
{
System.out.print("*");
}
}
While the outer loop is decrementing, the inner loop should be incrementing
The whole code will be:
Scanner kb = new Scanner(System.in);
System.out.println("Enter the number of your triangle (1 to 50):");
int userInput = kb.nextInt();//3
int minus = userInput -1;//2
int lineNumber = userInput + minus;//5
int half = (lineNumber / 2) + 1;//3
for(int i = 1; i <= half; i++){
System.out.println("");
for (int j = 1; j <= i; j++){
System.out.print("*");
}
}
for (int i = minus; i >= 1; i--){
System.out.println("");
for (int j = 1; j <= i; j++){
System.out.print("*");
}
}
Result:
This is a nice short way to do it:
private static void test(int n) {
char[] buf = new char[n];
Arrays.fill(buf, '*');
for (int row = 1 - n; row < n; row++)
System.out.println(new String(buf, 0, n - Math.abs(row)));
}
Test
public static void main(String[] args) {
test(5);
}
Output
*
**
***
****
*****
****
***
**
*
You can try something like this:
Scanner kb = new Scanner(System.in);
System.out.print("Enter the number of your triangle (1 to 50): ");
int input = kb.nextInt();
for (int i = 0; i < input; i++) {
System.out.println();
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
}
for (int i = input - 1; i > 0; i--) {
System.out.println();
for (int j = 0; j < i; j++) {
System.out.print("*");
}
}
Sample output for 5:
Enter the number of your triangle (1 to 50): 5
*
**
***
****
*****
****
***
**
*
Process finished with exit code 0
Change the inner loop to this. I tested it and it works great:
//for (int j = minus; j >= i; j--) // <--old line
for (int j = 0; j<i; j++) //<--new line
{
System.out.print("*");
}
You could try
for (int i = minus; i >= 1; i--)
{
System.out.println("");
for (int j = minus; j >= 0 /* it was i */; j--)
{
System.out.print("*");
}
}
or
int add = 1;
int asterics = 1;
while(asterics >0){
if(asterics == userInput)
{
add = -1; // switch to decrement
}
for(int i=0;i<asterics;i++){
System.out.print("*");
}
asterics += add;
}
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
*
***
*****
***
*