I am working on an assignment and I understand how to do the first part of the assignment but not the second.
Problem:
Write a program that ask the user to enter the size of a triangle (1 to 50), then print the triangle by printing a series of lines consisting of asterisks. The first line will have 1 asterisk, the next two will have 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 print one less asterisk and continue by decreasing the number of asterisk by 1 for each successive line until any one asterisk is printed.
I can make the program print up ward however I don't know how to make it print downward. My professor says to use for loops.
import java.util.Scanner;
public class CS123Ass5ID5189 {
public static void main(String[] args) {
int size;
System.out.println("Enter Triangle size");
Scanner key = new Scanner(System.in);
size = key.nextInt();
System.out.println(size);
for (int i = 0; i < size; i++) {
for (int f = 0; f < i; f++) {
System.out.print("*");
}
System.out.println("*");
}
for (int i = 0; i > size; i--) {
for (int f = 0; f > i; f--) {
System.out.println("*");
}
System.out.println("*");
}
}
}
Supposed to look something like
*
**
***
**
*
Your answer is almost there. You just need the second outer loop to count down from size to zero in the outer loop, and do the same thing.
for (int i = size - 1; i > 0; i--)
So the first loop goes from 0 to size, and this loop goes from (size - 1) to 0.
for (int i = size - 1; i > 0; i--) {
// This section is exactly the same as in the first loop
for (int f = 0; f < i; f++) {
System.out.print("*");
}
System.out.println("*");
}
Edit
To limit the input number to 50, check it in another loop. While the user has entered an invalid number, tell them, and ask for another one. Add this just after you get the initial number:
while (size < 0 || size > 50)
{
System.out.print("Size must be between 0 and 50. Try again: ");
size = key.nextInt();
}
Your second loop is wrong, it should be for i>0. Also, start at 1, not 0 and print like this:
for (int i = 1; i <= size; i++) {
for (int f = 0; f < i; f++) {
System.out.print("*");
}
System.out.println();
}
for (int i = size-1; i > 0; i--) {
for (int f = 0; f < i; f++) {
System.out.print("*");
}
System.out.println();
}
Your inner loop should still be counting up to the value of i. This should do what you need.
For loops can begin at any value, not just zero. This allows you to start at size and decrement all the way down to zero.
Here is an example of what you are looking for. (It links to an online executable to demonstrate the code below.)
public class Main
{
public static void main (String[] args)
{
int size = 10;
System.out.println(size);
for (int i=0; i<size-1; i++)
{
for (int f=0; f<i; f++)
{
System.out.print("*");
}
System.out.println("*");
}
for (int i=size-1; i>=0; i--)
{
for (int f=i; f>0; f--)
{
System.out.print("*");
}
System.out.println("*");
}
}
}
P.S. Your second inner for loop should have System.out.print not System.out.println to keep all the asterisks on one line.
Your first loop looks fine, but look at the second loop.
for (int i = 0; i > size; i--) {
for (int f = 0; f > i; f--) {
System.out.println("*");
If size is greater than 0, the outer for-loop won't be entered. Fix that by setting i = size - 1, then loop until i > 0 and i-- to decrease i in each loop.
The inner for loop has a similar problem, it should be the exact same and the previous inner loop. Also exact same in the usage of System.out.print instead of System.out.println. Otherwise, the triangle will print vertically for the bottom half.
FWIW - It's easier to read if you make small methods to clearly show your intention.
private static void printStarLine(int howManyStars) {
for (int i = 0; i < howManyStars; i++) {
System.out.print("*");
}
System.out.println();
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int size = 3; // some number in the range 1-50
do {
System.out.println("Enter Triangle size (1-50)");
size = key.nextInt();
} while (size < 1 || size > 50);
for (int stars = 1; stars < size; stars++) {
printStarLine(stars);
}
printStarLine(size);
for (int stars = size - 1; stars > 0; stars--) {
printStarLine(stars);
}
}
for(i=1; i<=n; i++)
{
for(j=1; j<=i; j++)
{
System.out.print("*");
}
System.out.println();
}
for(i=n; i>=1; i--)
{
for(j=1; j<i; j++)
{
System.out.print("*");
}
System.out.println();
}
this works
Related
How to make square matrix appear in a "snake" pattern? User inputs # of rows/columns in array and then matrix is displayed in ascending order but in a snake pattern.
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13
import java.util.Scanner;
public class A3_Q2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.println("[-------------------------]");
System.out.println("[ Array Pattern ]");
System.out.println("[-------------------------]");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
int arraySize = keyboard.nextInt();
while(arraySize < 3)
{
System.out.println("Lets try this again ....");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
arraySize = keyboard.nextInt();
}
int [][] pattern = new int[arraySize][arraySize];
int number = 1;
for (int i = 0; i <= arraySize -1; i++){
for(int j = 0; j <= arraySize - 1; j++)
{
pattern[i][j] = number;
number++;
System.out.printf("%3d", pattern[i][j]);
}
System.out.println("");
}
}
}
If we wanted to just print the 2D array in ascending order from left to right on each row, we could just use the following for loop:
for (int i=0; i < arraySize; ++i) {
for (int j=0; j < arraySize; ++j) {
System.out.printf("%3d", pattern[i][j]);
}
}
To get the reverse order effect you want, we only need to add logic such that for odd rows, we print a row backwards, from left to right:
for (int i=0; i < arraySize; ++i) {
if (i%2 == 0) {
// for even rows, print as we normally would
for (int j=0; j < arraySize; ++j) {
System.out.printf("%3d", pattern[i][j]);
}
}
else {
// for odd rows, iterate backwards over the array, the print left to right
for (int j=arraySize-1; j >= 0; --j) {
System.out.printf("%3d", pattern[i][j]);
}
}
System.out.println();
}
Update:
You can initialize your array using something like the following:
int arraySize = 4;
for (int i=0; i < arraySize; ++i) {
for (int j=0; j < arraySize; ++j) {
pattern[i][j] = i*arraySize + j + 1;
}
}
I am trying to System.out.print() a diamond out of *'s. So far I have spent a good 5 hours on trying to figure out how to reverse print the bottom triangle of the diamond.
I can worry about the spacing to complete the diamond later. (I have it worked for the most part).
If someone could explain to me what I am doing wrong and how the right way works I would greatly appreciate it.
private static void diamond()
{
int numLines = 0;
System.out.println("How many lines would you like in the Diamond?");
numLines = scan.nextInt();
if (numLines / 2 == 0) //if number is even, make odd.
{
numLines++;
}
for(int i = 0; i <= numLines ; i++) // Controls #Lines
{
if(i <= numLines / 2)
{
for(int j = 0; j < i * 2 - 1; j++) // Controls #Stars small upright triangle
{
System.out.print("*");
}
}
else
{
for(int k = numLines; k > i / 2; k--) // Controls # of spaces
{
System.out.print("*");
}
/*for(int j = numLines/2 - i, l = i; l > j; j++) // Controls #Stars small upright triangle
{
String stars = "*";
System.out.print(stars);
}*/
}
System.out.println("");
}
}
`
What happens to your attempt is that you loop through the half (of the lines) of your diamond [the number of lines in second/first half] times.
You'd want to do a if-statement each loop, not an if and a for in each loop
Probably you want this
Just adjust it for user input values
public static void main(String[] args) {
System.out.print("Reverse diamond: \n");
for (int i = 1; i < 10; i += 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.print("\n");
}
System.out.print("\n\nDiamond from starts: \n");
for (int i = 7; i > 0; i -= 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.print("\n");
}
}
output:
I am trying to make my code print out the Asterisk in the image, you see below. The Asterisk are align to the right and they have blank spaces under them. I can't figure out, how to make it go to the right. Here is my code:
public class Assn4 {
public static void main(String[] args) {
for (int i = 0; i <= 3; i++) {
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
for (int x = 0; x <= 1; x++) {
System.out.println(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
}
System.out.println();
}
}
Matrix problems are really helpful to understand loops..
Understanding of your problem:
1) First, printing star at the end- That means your first loop should be in decreasing order
for(int i =7;i>=0; i+=i-2)
2) Printing star in increasing order- That means your second loop should be in increasing order
for(int j =0;j<=7; j++)
Complete code:
for(int i =7;i>=0; i=i-2){ // i=i-2 because *s are getting incremented by 2
for(int j =0;j<=7; j++){
if(j>=i){ // if j >= i then print * else space(" ")
System.out.print("*");
}
else{
System.out.print(" ");
}
}
System.out.println();// a new line just after printing *s
}
Starting loops with 1 can sometimes help you visualize better.
int stopAt = 7;
for (int i = 1; i <= stopAt ; i += 2) {
for (int j = 1; j <= stopAt; j++) {
System.out.print(j <= stopAt - i ? " " : "*");
}
System.out.println();
}
Notice, how each row prints an odd number of *s ending at the line with 7. So, you start with i at 1 and go through 3 1+2, 5 3+2, and then stopAt 7 5+2.
The nested for loop has to print 7 characters always to make sure *s appear right aligned. So, the loop runs from 1 to 7.
Here the complete code:
for(int i = 0; i < 8; i++){
if( i%2 != 0){
for(int x = 0; x < i; x++){
System.out.print("*");
}
}else{
System.out.println();
}
}
You have an input of n and that represents half the rows that the diamond will have. I was able to make the first half of the diamond but I'm EXTREMELY frustrated with the second half. I just can't seem to get it. I'm not here to ask for specific code I need, but can you point me in the right direction and give me some tips/tricks on how to write this? Also, if I'm going about this program the wrong way, feel free to tell me and tell me on how I should approach the program.
The diamonds at the bottom represent an input of 5. n-1 represents the spaces to the left of each asterisk. Thank you for your help!
public static void printDiamond(int n)
{
for(int i=0;i<n;i++)
{
for(int a=0;a<(n-(i+1));a++)
{
System.out.print(" ");
}
System.out.print("*");
for(int b=0; b<(i*2);b++)
{
System.out.print("-");
}
System.out.print("*");
System.out.println();
}
}
** What I need ** What I have currently
*--* *--*
*----* *----*
*------* *------*
*--------* *--------*
*--------*
*------*
*----*
*--*
**
public static void main(String[] args) {
int n = 10;
for (int i = 1 ; i < n ; i += 2) {
for (int j = 0 ; j < n - 1 - i / 2 ; j++)
System.out.print(" ");
for (int j = 0 ; j < i ; j++)
System.out.print("*");
System.out.print("\n");
}
for (int i = 7 ; i > 0 ; i -= 2) {
for (int j = 0 ; j < 9 - i / 2 ; j++)
System.out.print(" ");
for (int j = 0 ; j < i ; j++)
System.out.print("*");
System.out.print("\n");
}
}
output
*
***
*****
*******
*********
*******
*****
***
*
Just reverse your loop :
for(int i=n-1;i>=0;i--)
{
for(int a=0;a<(n-(i+1));a++)
{
System.out.print(" ");
}
System.out.print("*");
for(int b=0; b<(i*2);b++)
{
System.out.print("-");
}
System.out.print("*");
System.out.println();
}
Since you have half the diamond already formed, simply run the loop again, in reverse, eg:
public static void printDiamond(int n)
{
for (int i = 0; i < n; i++)
{
for (int a = 0; a < (n - (i + 1)); a++)
{
System.out.print(" ");
}
System.out.print("*");
for (int b = 0; b < (i * 2); b++)
{
System.out.print("-");
}
System.out.print("*");
System.out.println();
}
for (int i = n-1; i >= 0; i--)
{
for (int a = 0; a < (n - (i + 1)); a++)
{
System.out.print(" ");
}
System.out.print("*");
for (int b = 0; b < (i * 2); b++)
{
System.out.print("-");
}
System.out.print("*");
System.out.println();
}
}
Whenever I see a symmetry of a kind, recursions ring to my head. I'm posting only for you and others interesting into learning more. When beginning, recursions can harder to grasp but since you already have loop based solutions, contrasting against recursion will clearly outline advantages and disadvantages. My advice, don't miss out on the chance to get into it :)
A recursive solution:
static int iteration = 0;
public static void printDiamond(int n) {
int numberOfBlanks = n - iteration;
int numberOfDashes = iteration * 2;
String blank = new String(new char[numberOfBlanks]).replace("\0", " ");
String dash = new String(new char[numberOfDashes]).replace("\0", "-");
String star = "*";
String row = blank + star + dash + star + blank;
// printing the rows forward
System.out.println(row);
iteration++;
if (iteration < n) {
printDiamond(n);
}
// printing the rows backward
System.out.println(row);
}
first, don't get confused with the strange new String(new char[numberOfBlanks]).replace("\0", " "); its a neat trick in java to construct a string with repeated chars, eg new String(new char[5]).replace("\0", "+"); would create the following String +++++
The recursion bit explained. The second println won't run until the recursion is stopped. The stop criteria is defined by iteration < n. Up until that point the rows up until that point will be printed. So something like this:
iteration 1. row = **
iteration 2. row = *--*
iteration 3. row = *----*
iteration 4. row = *------*
iteration 5. row = *--------*
than the recursion stops, and the rest of the code is executed but in reversed order. So only the second println is printed, and the value of row variable is like as follows
continuing after 5 iteration row = *--------*
continuing after 4 iteration row = *------*
continuing after 3 iteration row = *----*
continuing after 2 iteration row = *--*
continuing after 1 iteration row = **
I didn't go into mechanics behind it, plenty of resource, this is just to get you intrigued. Hope it helps, best
I am having difficulties with completing this program. I am trying to make a program that creates asteriks, but then makes it into a triangle.
This is what I have already.
public class 12345 {
public static void main(String[] args) {
int n = 0;
int spaces = n;
int ast;
System.out.println("Please enter a number from 1 - 50 and I will draw a triangle with these *");
Scanner keyboard = new Scanner(System.in);
n = keyboard.nextInt();
for (int i = 0; i < n; i++) {
ast = 2 * i + 1;
for (int j = 1; j <= spaces + ast; j++) {
if (j <= spaces)
System.out.print(' ');
else
System.out.print('*');
}
System.out.println();
spaces--;
}
}
}
It is creating the asteriks, but how would I be able to continue them where they make a triangle... so they get bigger as they go, and then back smaller...
Thank you in advance!
Try moving
int spaces = n;
to AFTER the value of n is read from stdin.
This solves half your problem and hopefully gets you on the right track.
I added a few things to your code and got it to print the full triangle, where the number input in the scanner will be the number of asterisks printed in the bottom row. I.e. if the input is 3, the triangle will be two rows of 1->3; if the input is 5 then the triangle will be 3 rows of 1->3->5, and so on.
public static void main(String[] args) {
int ast;
int reverse = 1;
System.out.println("Please enter a number from 1 - 50 and I will draw a triangle with these *");
Scanner keyboard = new Scanner(System.in);
int spaces = keyboard.nextInt();
for (int i = 0; i < spaces; i++) {
ast = 2 * i + 1;
for (int j = 1; j <= spaces + ast; j++) {
if (j <= spaces) {
System.out.print(' ');
} else {
System.out.print('*');}
if (j > spaces + ast) {
for (int k = 0; k < spaces-(reverse-1); k++) {
System.out.print(' ');
}
}
int k = 0;
reverse++;
}
System.out.println();
spaces--;
}
}
}
I added another if statement after your if-else that triggers when the variable j exceeds the first loop condition. This triggers another loop that makes the output lines symmetrical by essentially repeating your first if statement.
I hope this helps =)