"Skewed" Triangle with asterisks in Java [closed] - java

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;
}

Related

Q: How to write to the right side of the triangle? [duplicate]

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:
*
**
***

printing pyramid pattern with asterisks [duplicate]

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();
}
}

Can't figure out For Loop

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.

How do i draw an Arrow in Java?

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();
}

Nested for loops 0123

I need to create a nested for loops that gives the following output,
0
1
2
3
This is what I have, but for the second test, userNum is replaced by 6 and obviously my code fails.. help?
public class NestedLoop {
public static void main (String [] args) {
int userNum = 0;
int i = 0;
int j = 0;
for(i = 0; i <= userNum; i++){
System.out.println(i);
for(i = 1; i <= userNum; i++){
System.out.println(" " +i);
for(i = 2; i <= userNum; i++){
System.out.println(" " +i);
for(i = 3; i <= userNum; i++){
System.out.println(" " + i);
}
}
}
}
return;
}
}
I think (it's a guess, though) that you're looking for this.
public static void main (String [] args)
{
int limit = 6;
for(int i = 0; i <= limit; i++)
{
for(int j = 0; j < i; j++)
System.out.print(" ");
System.out.println(i);
}
}
The reason why your approach fails is, as I see it, that you are looping through the numbers to show (which is right) but you fail to loop up on the number of spaces (which I resolved by relating the inner loop's limit to the outer loop's current value.
Let's talk a bit about what your intention is with these loops.
The inner loop is meant to produce an arbitrary number of spaces, depending on what number you're iterating on. So if you're on number 0, you produce no spaces, and if you're on 1, you produce one space, and so forth. The other caveat is that they all must appear on the same line, so System.out.println is the incorrect choice.
You would want to use System.out.print to print out the spaces. So let's write that.
for(int j = 0; j < 6; j++) {
System.out.print(" ");
}
This will print out six spaces unconditionally. What that condition is depends on the current number we're iterating on. That comes from your outer loop.
You only need to define a loop that starts from an arbitrary starting point - like 0 - and then loop until you are at most your ending number. For this, your current loop is sufficient:
for(i = 0; i <= userNum; i++) {
}
Now, we need to bring the two pieces together. I leave the figuring out of the question mark and what to print after you've printed the spaces as an exercise to the user, bearing in mind that you must stop printing spaces after you've reached your number.
for(int i = 0; i <= userNum; i++) {
for(int j = 0; j < ?; j++) {
System.out.print(" ");
}
}
Let's analyse the task
In every line, we should print a number and different number spaces in the front of the number.
For that, we need two loops - one outer to iterate from 0 to N and one inner to add spaces in front of the number.
private static void method1(int userNum) {
int nummSpaces = 0;
for (int i = 0; i <= userNum; i++) {
for (int j = 0; j < nummSpaces; j++) {
System.out.print(" ");
}
nummSpaces++;
System.out.println(i);
}
}
In this solution, we have variable numSpaces which used to count the number of spaces in front of the number. It is unneeded - we can use variable i for that purpose.
private static void method2(int userNum) {
for (int i = 0; i <= userNum; i++) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
System.out.println(i);
}
}
Let's analyses once again the output
- the fist line: printed zero spaces and number 0
- the second line: printed one space and number 1
- the third line: printed two spaces and number 2
- and so on
Finally, we can use just one variable, which contains spaces and after that print the length of it:
private static void method3(int userNum) {
for (String spaces = ""; spaces.length() <= userNum; spaces += " ") {
System.out.println(spaces + spaces.length());
}
}
C/C++
#include <iostream>
using namespace std;
int main() {
int userNum;
int i;
int j;
cin >> userNum;
for (i = 0; i <= userNum; ++i) {
for (j = 0; j < i; ++j) {
cout << " ";
}
cout << i << endl;
}
return 0;
}

Categories