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

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

Related

Take in a positive integer n Create n triangles in stars with their bases below of size n each

Help with this question:
Take a positive integer n and form n triangles from stars with their base down of size n each.
For example, for input 3, the following output will be obtained:
* * *
** ** **
*** *** ***
Here's what I've tried.
import java.util.Scanner;
public class ex3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter n");
int n = input.nextInt();
while (n <= 0) {
System.out.println("error");
n = input.nextInt();
}
for (int r = 1; r <= n; r++) {
for (int c = 1; c <= n - r; c++)
System.out.print(" ");
for (int c = 1; c <= r; c++)
System.out.print("*");
System.out.println();
}
}
}
Here's my solution, with explanations in comments
import java.util.Scanner;
class Main {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in)) {
System.out.println("enter n");
int n = input.nextInt();
while (n <= 0) {
System.out.println("error");
n = input.nextInt();
}
for (int r = 1; r <= n; r++) { // <-- we will have to print n rows
printLine(n, r);
}
}
}
static void printLine(int n, int lineNumber) {
StringBuffer line = new StringBuffer();
for(int i = 0; i < n; i ++) { // <-- each line will have '*'s for n triangles
for(int j = lineNumber; j > 0; j--) { // <-- each line has as many '*'s as its line number, so print those first
line.append("*");
}
for(int j = 0; j < n - lineNumber + 1; j ++) { // <-- we then have to add enough spaces to leave room for the next triangle's '*'s
line.append(" ");
}
}
System.out.println(line.toString()); // <-- print the line we've built so far
}
}
EDIT:
Here's a replit that avoids one of the loops by using a modulo to print an entire line at once, and also uses recursion, for no real reason, in place of the outer-most loop: https://replit.com/#anqit/MicroExtrovertedTrace#Main.java
First, the blanks follow the stars, then, you have to repeat n times the two loops:
for (int r = 1; r <= n; r++) {
for (int t = 1; t <= n; t++) {
for (int c = 1; c <= r; c++)
System.out.print("*");
for (int c = 1; c <= n - r; c++)
System.out.print(" ");
}
System.out.println();
}
You have one for loop that prints out a single triangle of stars using nested for loops. The outer loop is responsible for the number of rows and the inner loops are responsible for printing the spaces and stars.
In my updated code, I added an outer loop that runs n times, and each time it runs, it prints out a triangle of stars. The inner loops are responsible for printing the stars of the triangle and spaces between the triangles.
The main difference is that in your first code, only one triangle is printed, while in my updated code, n triangles are printed. In addition, the indentation of the inner loops has been adjusted to align the triangles correctly on the same line.
import java.util.Scanner;
public class ex3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter n:");
int n = input.nextInt();
while (n <= 0) {
System.out.println("error: please enter a positive number:");
n = input.nextInt();
}
for (int r = 1; r <= n; r++) {
for (int t = 1; t <= n; t++) {
for (int c = 1; c <= r; c++) {
System.out.print("*");
}
for (int i = 0; i < n - r + 1; i++) {
System.out.print(" ");
}
}
System.out.println();
}
}
}
Here is a 3 forloop variant
int n = 4;
for (int i = 1; i <= n; i++) {
StringBuilder b = new StringBuilder("");
for (int s = 0; s < n; s++) {
b.append(s < i ? "*" : " ");
}
String line = b.append(" ").toString();//space between
for (int j = 1; j < n; j++) {
System.out.print(line);
}
System.out.println();
}
produces
> * * *
> ** ** **
> *** *** ***
> **** **** ****

How to make a numbers triangle in Java using loops, numbers starting from right

my project to create a triangle in Java with numbers starting from the right
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// loop
for (int i=1; i <= 6; i++) {
// space
for(int j=1; j <= 6-i; j++)
System.out.print(" ");
// numbers
for(int k= 1; k <= i; k++)
System.out.print(k);
// new line
System.out.println();
}
}
}
Here is one way. It uses String.repeat() to pad with leading spaces.
outer loop controls the rows.
Then print the leading spaces
inner loop iterates backwards, printing the value and a space
then print a newline
int rows = 6;
for (int i = 1; i <= rows; i++) {
System.out.print(" ".repeat(rows-i));
for (int k = i; k > 0; k--) {
System.out.print(k+ " ");
}
System.out.println();
}
prints
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
If you don't want to use String.repeat() then use a loop.
Well the only thing you have to do is change order like you are first adding space and then number instead add number and then space.
code -
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// loop
for (int i=1; i <= 6; i++) {
// numbers
for(int k= 1; k <= i; k++)
System.out.print(k);
// space
for(int j=1; j <= 6-i; j++)
System.out.print(" ");
// new line
System.out.println();
}
}
}
Now we get the result -
start k=i then decrement it till k>=1.
for(int k= i; k >=1 ; k--)
System.out.print(k+" ");
output
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int lines = scanner.nextInt();
for (int i = 0; i <= lines; i++) {
//space
int spaceNum = lines - I;
for (int j = 0; j < spaceNum; j++) {
System.out.print(" ");
}
//numbers
int numbers = lines - spaceNum;
for (int j = numbers; j > 0; j--) {
System.out.print(" " + j);
}
System.out.println();
}
}
}

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

"Skewed" Triangle with asterisks in Java [closed]

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

Making a block of X's with a number

I am trying to have the user enter a number and have the computer output a square with side of that number.
For example:
Enter a number:
4
XXXX
XXXX
XXXX
XXXX
I got this far, but don't know what else to do:
package blockmaker;
import java.util.*;
public class BlockMaker {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = scan.nextInt();
scan.nextLine();
for(int i = 0; i < number; i++){
System.out.println("X");
}
}
}
My current code outputs:
Enter a number:
4
X
X
X
X
Do I need to put a loop inside a loop?
Yes you need an inner loop for that:
for(int i = 0; i < number; i++){
for(int j = 0; j < number; j++) {
System.out.print("X");
}
System.out.println();
}
for(int i = 0; i < number; i++){
System.out.println("X"); // print X and new line
}
Above code prints "X" in each line.
Instead you need to print "X" number(n) times in each line. You need a nested loop.
for(int i = 0; i < number; i++){
for(int j = 0; j < number; j++)
System.out.print("X"); // print X - n times
System.out.println(); // print new line
}

Categories