I am trying to create a pattern in java by using a for-loop and nested for-loop based on the user input of a positive integer.
Here is an example:
User input = 5
Output:
5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5
This is what I have so far. I am getting a list of integers, but I cannot find out where to go from here to get a pattern such as the one above. All I am getting is "5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 "
System.out.print("Enter the value of n: ");
int n = scan.nextInt();
for (int row = 1; row <= n; row++) { //rows
for (int col = 1; col <= n; col++) { //columns
if (n - col + 1 <= n - row + 1 && row <= n && col <= n) { //what to print
System.out.print(n - row + 1 + " ");
} else if (n - col + 1 <= n - row + 1 && row <= n && col <= n) {
System.out.print(n - row + 1 + " ");
}
}
}
In this code I'm mirroring the column's and after that mirroring the rows. From mirroring I mean first creating mirror of the data.
First writing data to columns(left side) and then mirroring the column hence I get the right side of the column.
After writing data to the upper rows then mirroring the upper row I get bottom row.
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
public class Pattern {
static final PrintStream out = System.out;
public static void displayPattern(int n) {
final int arr[][] = new int[n * 2 - 1][];
for (int i = 0; i < arr.length; i++)
arr[i] = new int[n * 2 - 1];
final List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int current = n - i;
list.add(current);
for (int j = 0; j < list.size(); j++) {
arr[i][j] = list.get(j);
}
int remainings = n - list.size();
for (int j = list.size(), count = 0; count < remainings; j++, count++) {
arr[i][j] = current;
}
//writing data to right side of the columns(mirroring columns)
for (int j = n, count = 1; j < arr[i].length; j++, count++)
arr[i][j] = arr[i][j - count * 2];
}
//writing data to bottom half of the rows(mirroring rows)
for (int i = n, count = 1; i < n * 2 - 1; i++, count++) {
for (int j = 0; j < n * 2 - 1; j++)
arr[i][j] = arr[i - count * 2][j];
}
for (int a[] : arr) {
for (int b : a)
out.print(b + " ");
out.println();
}
}
public static void main(final String... $) {
displayPattern(5);
}
}
Output:
5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5
Related
I'm currently making a latin square that starts with a user-set number but for simplicity's sake I'll exclude Scanner code.
public static void main(String[] args){
int first = 2; // starting integer on square
int order = 4; //max integer
String space = new String(" ");
for (int row = 0; row < order; row++)
{
for (int column = 0; column < order; column++)
{
for (int shift = 0; shift < order; shift++)
{
int square = ((column+(first-1)) % order + 1); //this makes a basic square with no shifting
int latin = square+shift; //this is where my code becomes a mess
System.out.print(latin + space);
}
System.out.println();
}
}
}
}
Which prints out:
2 3 4 5
3 4 5 6
4 5 6 7
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
1 2 3 4
It's so close, considering the fact that it does start with my pre-determined first digit and it's printing only 4 integers.
The problem I'm running into is the fact that it's going further than my order integer and that it's printing double the rows.
Any idea what I can do to fix this?
For reference, this is what I want it to print:
2 3 4 1
3 4 1 2
4 1 2 3
1 2 3 4
It seems that the innermost loop for (int shift...) is redundant and it causes duplication of the output, the latin value should be calculated using row parameter:
public static void main(String args[]) {
int first = 2; // starting integer on square
int order = 4; //max integer
String space = " ";
for (int row = 0; row < order; row++) {
for (int column = 0; column < order; column++) {
int latin = (row + column + first - 1) % order + 1;
System.out.print(latin + space);
}
System.out.println();
}
}
Output:
2 3 4 1
3 4 1 2
4 1 2 3
1 2 3 4
I'm currently stuck on creating the other side of my pyramid. I would like for my program to ask the user for a number between 5 and 15. Use that number to print out a square and a triangle. I have been able to do everything up until I get to the pyramid. I can create one side of the pyramid but I noticed i'm overlooking something when it comes to creating the other side. Any guidance on putting me in the right direction would be greatly appreciated.
import java.util.Scanner;
public class doLoop {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int number;
final int minimum = 5;
final int maximum = 15;
do {
System.out.print("Enter a number between" + " " + minimum + " " + "and" + " " + maximum + ":" );
number = input.nextInt();
for(int i = 1; i <= number; i++) {
for(int j = 1; j <= number; j++) {
System.out.print(j + " ");
}
System.out.println();
}
for(int column = 1; column <= number; column++) {
for(int row = 1; row <= number ; row++) {
if(column >= row) {
System.out.print(row);
} else {
System.out.print(" ");
}
}
System.out.println(" ");
}
if (number <= minimum || number >= 15)
System.out.println("Sorry, invalid");
} while (number <= minimum || number >= maximum);
}
}
**Here is my current output:**
Enter a number between 5 and 15:5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1
12
123
1234
12345
Sorry, invalid
Enter a number between 5 and 15:
**This is what i'm working towards:**
Enter a number between 5 and 15: 2
Sorry, 2 is invalid. Please try again.
Enter a number between 5 and 15: 20
Sorry, 20 is invalid. Please try again.
Enter a number between 5 and 15: 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10
You code has multiple errors!!!
your code will loop forever
you don't need a do loop
If I understand correrctly your problem is that you want the left side of the pyramid. You can achieve it by looping from negative user input to the values inserted by the user
Here's a snipped code, you need some tweaking based on your needs!!!
import java.util.Scanner;
public class doLoop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
final int minimum = 5;
final int maximum = 15;
System.out.print("Enter a number between" + " " +
minimum + " " + "and" + " " + maximum + ":");
number = input.nextInt();
if (number <= minimum || number >= 15) {
System.out.println("Sorry, invalid");
return;
}
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= number; j++) {
System.out.print(j + " ");
}
System.out.println();
}
for (int row = 1; row < number; row++) {
for (int column = -(number - 1); column <= number; column++) {
int absValue = Math.abs(column);
// you need to use the absolute value
// to print the positive value and to perform column checks
if (absValue <= row)
System.out.print(absValue);
else {
// if the absolute value is greater the the current print 1 or 2 spaces
// based on the value of the column
//(2 spaces if lower then 10 otherwise 1 space only)
System.out.print(absValue < 10 ? " " : " ");
}
// If the absolute value of column is -1 or 1 you need to change
// the value to "1" to bypass the printing of 101
if (absValue == 1)
{
column = 1;
}
}
System.out.println();
}
}
}
I would rather edit what I have worked on as opposed to just copying what you did. Plus, I don't understand all of your code. I was able to complete the triangle I was looking for. But for some reason I can't get my loop to follow the conditions I set. It worked initially before I added the for loops for the shapes but now i'm stuck on how to get it to follow them again. Any advice?
import java.util.Scanner;
public class doLoop {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int number;
final int minimum = 5;
final int maximum = 15;
do {
System.out.print("Enter a number between" + " " + minimum + " " + "and" + " " + maximum + ":" );
number = input.nextInt();
if (number <= minimum || number >= maximum) {
System.out.println("Sorry, invalid");
break;
}
for(int i = 1; i <= number; i++) {
for(int j = 1; j <= number; j++) {
System.out.print(j + " ");
}
System.out.println();
}
int columns = 1;
for (int i = number; i >= 1; i--)
{
for (int j = 1; j <= i*2; j++)
{
System.out.print(" ");
}
for (int j = i; j <= number; j++)
{
System.out.print(j + " ");
}
for (int j = number - 1; j >= i; j--)
{
System.out.printf(j + " ");
}
System.out.println();
columns++;
}
} while (number <= minimum || number >= maximum);
}
}
I'm wondering what is the difference between these loops in 2D arrays:
for (int r = row - 1, c = column - 1; r >= 0 && c >= 0; r--, c--) {
...
}
for(int r=row-1;r>=0;r--){
for(int c=column-1;c>=0;c--){
...
}
}
for (int r = row - 1, c = column - 1; r >= 0 && c >= 0; r--, c--)
The first example is one loop that decrements both r and c every cycle, meaning that the indices r and c will draw a diagonal starting at array[row-1][column-1].
for(int r=row-1;r>=0;r--){
for(int c=column-1;c>=0;c--){
The second example calls a loop for columns for each index of row, so it will access all the indices array[r][c]
I assume you are asking for the difference between a single outer loop and a nested loop. The difference is that the single loop will iterate over the diagonal of the 2D array and the nested loops with iterate over every index of the array. For instance, if there are 6 rows and 4 columns then:
for (int r = row - 1, c = column - 1; r >= 0 && c >= 0; r--, c--) {
System.out.println(r + " " + c);
}
will yield:
5 3
4 2
3 1
2 0
Whereas the nested loop
for(int r=row-1; r>=0; r--) {
for(int c=column-1; c>=0; c--) {
System.out.println(r + " " + c);
}
}
would yield
5 3
5 2
5 1
5 0
4 3
4 2
4 1
4 0
3 3
3 2
3 1
3 0
2 3
2 2
2 1
2 0
1 3
1 2
1 1
1 0
0 3
0 2
0 1
0 0
The first iterates for n times, where n is the least of row and column. The second iterates for m times, where m is row * column. That is
Math.min(row, column)
and
row * column
respectively.
It was so hard to ask such a newbie question on this advanced site. But after so much tries and even loosing my hope i was forced to bring my self here. I am not been able to print the following pattern:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
But with my tiresome efforts i reached the following:
public static void main(String[] args) {
int num = 1;
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15 - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print(num + " ");
}
System.out.println();
}
}
1
1 1
1 1 1
1 1 1 1
1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1
Here ya go
public static void main(String[] args) {
int max = 6;
int padLength = (int) Math.ceil(Math.log10(Math.pow(2, max) + 1)) + 2;
for (int i = 0; i < max; i++) {
for (int j = 1; j < max - i; j++) {
System.out.print(pad(" ", padLength));
}
for (int k = 0; k <= i; k++) {
System.out.print(pad(Math.pow(2, k), padLength));
}
for (int k = i - 1; k >= 0; k--) {
System.out.print(pad(Math.pow(2, k), padLength));
}
System.out.println();
}
}
public static String pad(double d, int l) {
Integer i = (int) d;
return pad(i.toString(), l);
}
public static String pad(String s, int l) {
return String.format("%-" + l + "s", s);
}
Explanation
int padLength = (int) Math.ceil(Math.log10(Math.pow(2, max) + 1)) + 2;
Math.pow(2,max) - Gives me maximal number I will have to display
Math.ceil(Math.log10(number + 1)) - I use this to determine length of string representation of specific number. Please refer to wikipedia to check what logarithm is. I add 1 to skip edge case when number is exact power of 10 e.g. log10(10)->1 (this will never occur in task specified in question, it's just for purity of solution). Ceil just rounds number up.
+2 - minimum gap between two numbers is specified example was 2 spaces long so I just add this
You could use here Integer.toString(((int)Math.pow(2, max))).length()+2 but it's not as pretty :)
return String.format("%-" + l + "s", s);
First I build format string that looks like e.g. %-3s, which means print String with minimum length of 3, padding on the right. Second argument is the String I want to print. Refer to documentation
Running example
I find the other answer very overwhelming and dramatic. You don't need much maths and complexity to solve this problem. This might not be the best code but I think it is easy to understand. Not even an explanation is needed, it is a row by row approach, It's good to keep things simple.
public static void main(String[] args) {
// Init
int row = 0;
int maxRows = 6;
int num = 1;
int indent = maxRows - 1;
// Printing loop
while (row < maxRows) {
// Indent
for (int i = 0; i < indent; ++i)
System.out.print(" ");
// Print nums
for (int i = 0; i < num; ++i)
System.out.printf("%4d", (int) Math.pow(2.0, i));
for (int i = num - 2; i >= 0; --i)
System.out.printf("%4d", (int) Math.pow(2.0, i));
// New line
System.out.println("");
// Adjustments
++row;
--indent;
++num;
}
Output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
I need help. My assignment is to write a Java program using nested loops to print out the following output pattern:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
//pattern1
for(int outer=1;outer<=6;outer++) // outer loop controls number of rows
{
for(int inner=1;inner<=outer; inner++) // another loop to control number of numbers in each row.
{
System.out.print(inner);
}
System.out.println(); // move the cursor from the end of the current line to the beggiing to the next line
}
//pattern 2
for(int outer =1; outer<=6 ; outer++) //outer loop controls number of rows
{
//3-1 create spaces before numbers.
for(int space=1; space<=6-outer; space++ ) //group controls number of spaces
{
System.out.print(" ");
}
//3-2 print out real numbers.
for(int inner=1;inner<=outer; inner++) // another loop to control number of numbers in each row.
{
System.out.print(inner);
}
System.out.println();
}
Those two codes are back to back, but I do not understand how I would make the numbers 2 4 8 16 etc show up, and put them back to back.
What's wrong with my code? Is there a better way of doing this in Java?
A simple version with bit shifting and static column size / padding - could be improved by using Math.getExponent() for dynamically repeating spaces and format %3d ...
public static void f(int n) {
for (int i = 0; i < n; i++) {
for (int l = n - i; l > 0; l--) { // padding for symmetry
System.out.print(" ");
}
for (int j = 0; j <= i; j++) { // "left side" of pyramid
System.out.printf("%3d ", 1 << j);
}
for (int k = i - 1; k >= 0; k--) { // "right side" of pyramid
System.out.printf("%3d ", 1 << k);
}
System.out.println();
}
}
Output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
You're going to use a nested loop with an if statement controlling the output.
This code should help you with your formatting. You'll have to figure out how to add the || so that it flips the triangle and how to format your print statements so it looks like that.
int totalWidth = 8;
for (int row = 1; row <= totalWidth; row++) {
for (int col = 1; col <= totalWidth; col++) {
if (col <= totalWidth - row) {
System.out.print(" ");
}else {
System.out.print("*");
}
}
System.out.println();
}
It will output
*
**
***
****
*****
******
*******
********
public class pyramid
public static void f(int n) {
for (int i = 0; i < n; i++) {
for (int l = n - i; l > 0; l--) { // padding for symmetry
System.out.print(" ");
}
for (int j = 0; j <= i; j++) { // "left side" of pyramid
System.out.printf("%3d ", 1 << j);
}
for (int k = i - 1; k >= 0; k--) { // "right side" of pyramid
System.out.printf("%3d ", 1 << k);
}
System.out.println();
}
}