half the pyramid is inverted with an even number, and each line omits the starting and ending numbers, so that the output expectation are as shown below.
Expected output
2 4 6 8 10
4 6 8
6
but I have tried my code below with the results that do not match my expectations.
My code
public static void main(String[] args) {
int rows = 5;
for (int i = rows; i >=1 ; i--) {
for (int j = 1; j <=2*i ; j++) {
if (j % 2 == 0){
System.out.print(j + " ");
}
}
System.out.println();
}
}
My output
2 4 6 8 10
2 4 6 8
2 4 6
2 4
2
Question:
how to solve the problem is?
You need to change the starting value of j as well and limit how often your first loop runs depending on rows:
int rows = 5;
for (int i = rows; i >= rows / 2; i--) {
for (int j = 2 + 2 * (rows - i); j <= 2 * i; j += 2) {
System.out.print(j + " ");
}
System.out.println();
}
Currently, you are starting the inner loop as int j = 1. Instead of a fixed start, it should be variable.
Replace
int j = 1;
with
int j = 2 * (rows - i + 1) - 1;
The starting condition of j should depend on i, also you can remove the if using j += 2 as increment statement
int rows = 5;
for (int i = rows; i >= 1; i--) {
for (int j = 2 * (rows - i + 1); j <= 2 * i; j += 2) {
System.out.print(j + " ");
}
System.out.println();
}
'rows' is a bad name. Can you see why?
here's the code:
public static void main(String[] args) {
int columns = 5;
for (int currentColumn = 0; currentColumn < columns ; currentColumn++) {
for (int j = currentColumn; j < columns-currentColumn ; j++) {
System.out.print((2*j+2) + " ");
}
System.out.println();
}
}
First, try to understand the pattern. For each iteration, the number of elements in a column is decreasing by 2. So consider the below code
public static void main(String[] args) {
int input = 5, multiplier = 2;
for(int numberOfRows = input; numberOfRows >= 1; numberOfRows -= 2) {
for(int columns = 1; columns <= numberOfRows; columns += 1) {
System.out.print(columns * multiplier + "\t");
}
System.out.println();
}
}
Related
So I have been asked this question and I could only solve the top part of the code, I am stuck on the bottom part.
Write a Java program called EmptyDiamond.java that contains a method that takes an integer n and prints a empty rhombus on 2n − 1 lines as shown below. Sample output where n = 3:
1
2 2
3 3
2 2
1
Here's my code so far:
public static void shape(int n) {
//TOP PART
for (int i = 1; i <= (n - 1); i++) {
System.out.print(" ");
}
System.out.println(1);
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= (n - i); j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= 2 * i - n + 1; j++) {
System.out.print(" ");
}
System.out.println(i);
}
//BOTTOM PART (The messed up part)
for (int i = n + 1; i <= 2 * n - 2; i++) {
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= n; j++) {
System.out.print(" ");
}
System.out.print(i);
}
for (int i = 1; i <= (n - 1); i++) {
System.out.print(" ");
}
System.out.println(1);
}
public static void main(String[] args) {
shape(4);
}
Maybe a little bit late, but because the bottom part of your message is just the first part mirrored you can use a Stack to print the message in reverse order:
public static void main(String[] args) {
int maxNumber = 3;
Stack<String> message = new Stack<>();
// upper part
for (int row = 0; row < maxNumber; row++) {
int prefix = maxNumber - (row + 1);
int spaces = row >= 2 ? row * 2 - 1 : row;
String line = getLine(row, prefix, spaces);
System.out.println(line);
if (row != maxNumber - 1)
message.add(line);
}
// bottom part
while (!message.isEmpty())
System.out.println(message.pop());
}
public static String getLine(int row, int prefix, int spaces) {
StringBuilder line = new StringBuilder("_".repeat(prefix));
line.append(row + 1);
if (row != 0) {
line.append("_".repeat(spaces));
line.append(row + 1);
}
return line.toString();
}
Output:
__1
_2_2
3___3
_2_2
__1
You can of course use any method you want to fill the stack (i.e. to generate the upper part of your message) like with the method this question suggessted. This upper part I describe contains the first line (inclusive) up to the middle line (exclusive).
Here is the program for printing empty diamond:
int n = 3; //change the value of n to increase the size of diamond
int upperCount = 1;
for (int i = n; i >= 1; i--) {
for (int j = i; j >= 1; j--) {
System.out.print(" ");
}
System.out.print(upperCount);
for (int j = 0; j <= upperCount - 2; j++) {
System.out.print(" ");
}
for (int j = 0; j <= upperCount - 2; j++) {
System.out.print(" ");
}
if (upperCount != 1) {
System.out.print(upperCount);
}
upperCount++;
System.out.print("\n");
}
int lowerCount = n - 1;
for (int i = 1; i <= n - 1; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(" ");
}
System.out.print(lowerCount);
for (int j = 0; j <= lowerCount - 2; j++) {
System.out.print(" ");
}
for (int j = 0; j <= lowerCount - 2; j++) {
System.out.print(" ");
}
if (lowerCount != 1) {
System.out.print(lowerCount);
}
lowerCount--;
System.out.print("\n");
}
Do following changes in the Bottom Part of your code:
int lowerCount = n - 1;
for (int i = n - 1; i >= 2; i--) {
for (int j = 1; j <= (n - i); j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= lowerCount; j++) {
System.out.print(" ");
}
System.out.print(i);
lowerCount -= 2;
}
You can print an empty diamond shape with numbers using two nested for loops over rows and columns from -n to n. The diamond shape is obtained when iAbs + jAbs == n:
int n = 2;
for (int i = -n; i <= n; i++) {
// absolute value of 'i'
int iAbs = Math.abs(i);
for (int j = -n; j <= n; j++) {
// absolute value of 'j'
int jAbs = Math.abs(j);
// empty diamond shape
System.out.print(iAbs + jAbs == n ? jAbs + 1 : " ");
if (j < n) {
System.out.print(" ");
} else {
System.out.println();
}
}
}
Output:
1
2 2
3 3
2 2
1
You can separately define width and height:
int m = 4;
int n = 2;
int max = Math.max(m, n);
for (int i = -m; i <= m; i++) {
// absolute value of 'i'
int iAbs = Math.abs(i);
for (int j = -n; j <= n; j++) {
// absolute value of 'j'
int jAbs = Math.abs(j);
// empty diamond shape
System.out.print(iAbs + jAbs == max ? jAbs + 1 : " ");
if (j < n) {
System.out.print(" ");
} else {
System.out.println();
}
}
}
Output:
1
2 2
3 3
3 3
2 2
1
See also:
• Filling a 2d array with numbers in a rhombus form
• How to print a diamond of random numbers?
java-11
Using String#repeat introduced as part of Java-11, you can do it using a single loop.
public class Main {
public static void main(String[] args) {
int n = 3;
for (int i = 1 - n; i < n; i++) {
int x = Math.abs(i);
System.out.println(" ".repeat(x) + (n - x)
+ " ".repeat(Math.abs((n - x) * 2 - 3))
+ ((i == 1 - n || i == n - 1) ? "" : (n - x)));
}
}
}
Output:
1
2 2
3 3
2 2
1
You can print a variant of the diamond simply by increasing the amount of space by one character:
public class Main {
public static void main(String[] args) {
int n = 3;
for (int i = 1 - n; i < n; i++) {
int x = Math.abs(i);
System.out.println(" ".repeat(x) + (n - x)
+ " ".repeat(Math.abs((n - x) * 2 - 3))
+ ((i == 1 - n || i == n - 1) ? "" : (n - x)));
}
}
}
Output:
1
2 2
3 3
2 2
1
Alternative solution:
public static void main(String[] args) {
int n = 7;
for (int i = -n; i <= n; i++) {
for (int j = -n; j <= n; j++) {
// edge of the diamond
int edge = Math.abs(i) + Math.abs(j);
// diamond shape with numbers
if (edge == n) System.out.print(n - Math.abs(i) + 1);
// beyond the edge && in chessboard order || vertical borders
else if (edge > n && (i + j) % 2 != 0 || Math.abs(j) == n)
System.out.print("*");
// empty part
else System.out.print(" ");
}
System.out.println();
}
}
Output:
** * * 1 * * **
* * * 2 2 * * *
** * 3 3 * **
* * 4 4 * *
** 5 5 **
* 6 6 *
*7 7*
8 8
*7 7*
* 6 6 *
** 5 5 **
* * 4 4 * *
** * 3 3 * **
* * * 2 2 * * *
** * * 1 * * **
See also: How to print a given diamond pattern in Java?
Solution: Java program called EmptyDiamond.java that contains a method that takes an integer n and prints a empty rhombus on 2n − 1 lines.
public class EmptyDiamond {
public static void main(String[] args) {
shape(3); // Change n to increase size of diamond
}
public static void shape(int n) {
int max = 2 * n - 1; // length of the diamond - top to bottom
int loop = 0; // with of each loop. initialized with 0
for (int i = 1; i <= max; i++) {
int val = 0;
if (i <= n) {
loop = n + i - 1;// e.g. when i = 2 and n = 3 loop 4 times
val = i; // value to be printed in each loop ascending
} else {
loop = n + (max - i); //e.g. when i = 4 and n = 3 loop 4 times
val = max - i + 1; // value to be printed in each loop descending
}
for (int j = 1; j <= loop; j++) {
// (value end of loop)
// || (value in the beginning when i <= n)
// || (value in the beginning when i > n)
if (j == loop
|| j == (n - i + 1)
|| j == (n - val + 1)) {
System.out.print(val); // Print values
} else {
System.out.print(" "); // Print space
}
}
System.out.println(); // Print next line
}
}
}
Output when n = 3:
1
2 2
3 3
2 2
1
Stream-only function:
public static void printEmptyDiamond(int n) {
IntStream.range(1, 2*n)
.map(i-> i > n ? 2*n-i : i)
.mapToObj(i -> " ".repeat(n-i) + i + (i>1 ? " ".repeat(2*(i-1)-1)+i : ""))
.forEach(System.out::println);
}
Example output (printEmptyDiamond(7)):
1
2 2
3 3
4 4
5 5
6 6
7 7
6 6
5 5
4 4
3 3
2 2
1
With explainations:
public static void printEmptyDiamond(int n) {
IntStream.range(1, 2*n)
.map(i-> i > n? 2*n-i : i) // numbers from 1 to n ascending, then descending to 1 again
.mapToObj(i -> " ".repeat(n-i) // leading spaces
+ i // leading number
+ (i>1 ? // only when number is > 1
" ".repeat(2*(i-1)-1) // middle spaces
+ i // trailing number
: ""))
.forEach (System.out::println);
}
I did it for fun, here's the code :
import java.util.Scanner;
public class Diamond {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int num = read.nextInt();
read.nextLine();
//TOP
for(int i = 1;i<=num;i++) {
//LEFT
for(int k = i; k<num;k++) {
if ( k % 2 == 0 ) {
System.out.print(" ");
}
else {
System.out.print(" ");
}
}
if(i>1) {
for(int j =1;j<=i;j++) {
if (j==1 || j== i) {
for(int u=0;u<j;u++) {
System.out.print(" ");
}
System.out.print(i);
}
else {
System.out.print(" ");
}
}
System.out.println("");
}
else {
System.out.println(" "+i);
}
}
//BOTTOM
for(int i = num-1;i>0;i--) {
for(int k = i; k<num;k++) {
if ( k % 2 == 0 ) {
System.out.print(" ");
}
else {
System.out.print(" ");
}
}
if(i>1) {
for(int j =1;j<=i;j++) {
if (j==1 || j== i) {
for(int u=0;u<j;u++) {
System.out.print(" ");
}
System.out.print(i);
}
else {
System.out.print(" ");
}
}
System.out.println("");
}
else {
System.out.println(" "+i);
}
}
}
}
And the output :
7
1
2 2
3 3
4 4
5 5
6 6
7 7
6 6
5 5
4 4
3 3
2 2
1
Having seen the other answers, there's a whole load of loops I could've skipped. Just decided to wing it at the end and do it as quick as possible.
Number Pattern
I am asked to enter a number rc, and based on rc construct this pattern. I am able to initialize the table but without the highlighted numbers:
int [][] num2 = new int [rc][rc];
counter = 1;
for(int i = 0; i < rc; i++){
if(i!=0)
counter--;
for(int j =0; j < rc; j++){
num2 [i] [j] = counter;
counter ++;
}
}
Any hints or ideas?
You got it partially right. The numbers printed on each row are the same but the start point is incremented by 1 each time. Thus, you can use variable i again to shift it.
int [][] num2 = new int [rc][rc];
int counter = 1;
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
num2[i][(j + i) % rc] = counter++;
}
}
The following code is working fine for your problem.
int rc=5;
int [][] num2 = new int [rc][rc];
int counter = 1;
for(int i = 0; i < rc; i++){
for(int j =i; j < rc; j++){
num2 [i] [j] = counter;
counter ++;
}
for(int k =0; k < rc; k++){
if(num2[i][k]==0){
num2 [i] [k] = counter;
counter++;
}
System.out.print(num2[i][k]+"\t");
}
System.out.println();
}
The logic behind my solution is:
First fill an array from 1 - N, where N is the user input (or
rc in this case):
Then, we check if it's not the first line, if it is, we simply print
the numbers in order.
Now, we have to know which numbers go first:
In the line 1 (remember it starts from 0), it must print the number at [1][4] in [1][0], so our loop substracts rc - i + j, this gives: 5 - 1 + 0, which in fact is index [4].
We know that after we've printed the last numbers first, we must continue the sequence, so we print index: [1][0] at [1][1] (Why 1, 2? Because otherwise we would get something like the example below, that's why we need to substract 1 to it
1 2 3 4 5
10 7 8 9 10
And that's it:
public class StrangePattern {
public static void main(String[] args) {
int rc = 5;
int number = 1;
int spaces = 0;
int[][] numbers = new int[rc][rc];
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
numbers[i][j] = number;
number++;
}
}
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
if (i != 0) {
if (j < i) {
System.out.print(numbers[i][rc - i + j] + "\t");
} else {
System.out.print(numbers[i][j - spaces] + "\t");
}
} else {
System.out.print(numbers[i][j] + "\t");
}
}
spaces++;
System.out.println();
}
}
}
Which provides this output:
1 2 3 4 5
10 6 7 8 9
14 15 11 12 13
18 19 20 16 17
22 23 24 25 21
And this one for rc = 3:
1 2 3
6 4 5
8 9 7
I have to make a pattern that is of a diamond shape such as this:
1
1 2
1 2 3
1 2 3 4 5
1 2 3
1 2
1
I wrote this ( sorry if for the variable name, this is just a small part of my program and I'm trying to get the pattern right so I didn't mind my variables at the moment):
public class NewFile{
public static void main(String []args){
int k = 0;
for (int i=1 ; i<=5 ; i++)
{
{ for (int h=2 ; h >= i ; h--)
System.out.print(" ");
for (int j=1 ; j<= i + k ; j++)
System.out.print(j);
for (int w=2 ; w>= i; w--)
System.out.print(" ");
}
k++;
System.out.println();}
}
}
My output is the following:
1
123
12345
1234567
123456789
I realize I should divide the code into a lower and upper triangle using two loops. However, I don't know how to break the first part. I did find the "trend" but I don't see how to implement it.
The following code will display a diamond shape that is made up of asterisks:
int i = 0, j, k, n;
n = 7; // 7 characters high. Change as needed.
for (k = 1; k <= (n + 1) / 2; k++) {
for (i = 0; i < n - k; i++) {
System.out.print(" ");
}
for (j = 0; j < k; j++) {
System.out.print("* ");
}
System.out.println("");
}
for (k = ((n + 1) / 2); k < n; k++) {
for (i = 1; i < k; i++) {
System.out.print(" ");
}
for (j = 0; j < n - k; j++) {
System.out.print(" *");
}
System.out.println("");
}
The integer n represents the height of the diamond in characters and can be changed as needed.
I tried like this,
for (int j = 1; j <= 4; j++) {
for (int k = 1; k < 10; k++) {
if (k <= j) {
System.out.print(k + " ");
} else
break;
}
System.out.println();
}
but it prints like
1
1 2
1 2 3
1 2 3 4
This question is asked in one interview i had attended, my mind is breaking to find solution.. i can't think..
init a variable before
int printed = 1;
and change your
System.out.print(k+" ");
with
System.out.print(printed+" ");
printed++;
This will do it :
public static void main(String[] args)
{
int i, j, k;
for (i = 1, j = 1; i < 11; j++)
{
for (k = 0; k < j; k++)
{
System.out.print(i++ + " ");
}
System.out.println();
}
}
This code will do that:
int i, j, k;
for (i = 1, j = 1; i < 11; j++) {
for (k = 0; k < j; k++)
System.out.print(i++ + " ");
System.out.print("\n");
}
Basically, i controls the next number to print, and j controls how many numbers you will print in the current line. k is just a counter for j.
You can also try this with some mathematic magic (sequences).
for (int j = 1; j <= 4; j++) {
for (int k=(int) (0.5*(Math.pow(j,2)-j+2));k<=(int) (0.5*j*(j+1));k++) {
System.out.print(k + " ");
}
System.out.println();
}
I need help, I got a problem with this matrix, I need to have it in this way:
1 2 3 4 = 10
2 4 6 8 = 20
3 6 9 12 = 30
4 8 12 16 = 40
But I have it in this way:
1 2 3 4 1
2 4 6 8 2
3 6 9 12 3
4 8 12 16 4
I dont know how can we do that, I intent but nothing
This is my code:
public class Matrix {
public static void main(String args[]) {
int mult = 4;
for (int i = 1; i <= mult; i++) {
// System.out.println();
for (int j = 1; j <= mult; j++) {
int operacion = i * j;
int suma = 0;
suma = operacion + suma;
System.out.print(operacion + " ");
}
int sum = 0;
sum = i + sum;
System.out.println(sum);
}
}
}
bye
When you do this:
for (int j = 1; j <= mult; j++) {
int operacion = i * j;
int suma = 0;
suma = operacion + suma;
suma is always equal to operacion, because you set it to 0 every time and then add operacion.
You want to do this:
int suma = 0;
for (int j = 1; j <= mult; j++) {
int operacion = i * j;
suma += operacion;
Put int sum = 0 outside the second for loop.
int suma = 0;
for (int i = 1; i <= mult; i++) {
// System.out.println();
suma =0;
for (int j = 1; j <= mult; j++) {
int operacion = i * j;
suma = operacion + suma;
System.out.print(operacion + " ");
}
System.out.println(suma);
}
You should take a look to String.format() or PrintStream.printf(). I think others allready helped you with the sum-problem. So try to print the values out like this:
for (int i = 0; i < 4; i++)
{
int[] values = new int[4];
int sum = 0;
for (int j = 0; j < 4; j++)
{
values[i] = (i+1) * (j+1);
sum += values[i];
}
System.out.printf("%-4d%-4d%-4d%-4d = %d\n", values[0], values[1], values[2], values[3], sum);
}
Try also to remove all the minus signs (-) from the last line and see what you like the most.
You are resetting sum to 0 just before you use it. You probably want for sum to be reset before your inner loop, added to inside your inner loop and printed outside your inner loop.
Also for your final println, print (" = " + sum) instead of just sum.
Trying not to actually correct your code since you mentioned this is an exercise (homework)--and thank you for tagging it. I wish more answerers would look for that sign as an indication that the person needs to learn and doesn't need the answer coded for them.