I want to print asterix which is equals the number of rows - (they should begin from the right side). It should begin with 9 spaces and 1 * at the first line, then 2 * and 8 spaces at the second line and so on until the tenth row which should have 10 * and 0 spaces like the image below:
I can print the right number of spaces at each line and 1 * at the right position. For example it prints 9 spaces and 1 * at the first line. But then at the second line it prints 8 spaces and 1 * at the ninth position instead of two?? I can't see what I have missed in my code:
for (int row = 1; row <= 10; row++) {
for (int col = 10; col > row; col--) {
System.out.print(" ");
if (col <= row) {
System.out.print("*");
}
}
System.out.println("*");
}
There are several solutions:
1) Either you create two inner loops for each row: one to write the spaces and another to write the stars
final int rows = 10;
for(int row = 1; row <= rows; row++) {
for(int i = 0; i < (rows - row); i++) {
System.out.print(" ");
}
for(int i = 0; i < (row); i++) {
System.out.print("*");
}
System.out.println();
}
2) Or you create one inner loops for each row and check the index to consider if you have to print a star or a blank.
final int rows = 10;
for(int row = 1; row <= rows; row++) {
for(int col = 1; col <= rows; col++) {
System.out.print((col <=(rows - row))? " " : "*");
}
System.out.println();
}
3) Or you can use string manipulation with subString (this is ugly but why not):
final int rows = 10;
final String stars = "************************";
final String blanks = " ";
for(int row = 1; row <= rows; row++) {
System.out.print(blanks.substring(0, rows - row));
System.out.println(stars.substring(0, row));
}
This might also be helpful:
int n = 10;
int k = 2 * n - 2; // number of spaces
// outer loop to handle number of rows
for (int i = 1; i <= n; i++) {
// inner loop to handle number spaces
for (int j = 1; j <= k; j++) {
System.out.print(" "); // printing spaces
}
k = k - 2; // decrementing k after each loop
// inner loop to handle number of columns
for (int j = 1; j <= i; j++) {
System.out.print("* "); // printing stars
}
// ending line after each row
System.out.println();
}
Related
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();
}
}
How can I print this using for loops?
1
22
333
4444
55555
I have tried this. But it is not printing what I want to print.
public class void main(String[] args) {
int last = 5, first = 1;
for (int i = 1; i <= last; i++) {
for (int j = last; j > i; j++) {
System.out.print(" ");
}
for (int k = i; k >= 1; k--){
System.out.print(k);
}
System.out.println();
}
}
It just prints this.
1
21
321
4321
54321
As you can see the first time you print, it is correct, then is when k is equal to i, so just print i
System.out.print(i);
edit
As per your edited code, do my above change, plsu
for (int j = last; j > i; j--) {
output
1
22
333
4444
55555
final
int last = 5;
for (int i = 1; i <= last; i++) {
for (int j = last; j > i; j--) {
System.out.print(" ");
}
for (int k = i; k >= 1; k--){
System.out.print(i);
}
System.out.println();
}
Your new problem solution just change k into i System.out.print(i)
int last = 5, first = 1;
for (int i = 1; i <= last; i++) {
for (int j = last; j > i; j--) {
System.out.print(" ");
}
for (int k = i; k >= 1; k--){
System.out.print(i);
}
System.out.println();
}
Output:
1
22
333
4444
55555
To get working code, it's helpful to first describe the detailed solution in words. That might be:
To print a triangle of height height, individually print each row from 1 to n.
To print a single row row, determine:
How many spaces it needs.
How many digits it needs.
Which digit to print.
The digit to print is the same as the row number row.
The number of digits digits is also the same as the row number row.
The number of spaces spaces depends on how long the line should be in total.
The number of spaces is width - digits.
To print a character repeatedly, use a for loop counting from 0 up to but excluding the repetition.
This description then translates into this code:
public static void main(String[] args) {
int height = 5;
int width = height; // can also be larger than height
for (int row = 1; row <= height; row++) {
int digit = row;
int digits = row;
int spaces = width - digits;
for (int i = 0; i < spaces; i++) {
System.out.print(' ');
}
for (int i = 0; i < digits; i++) {
System.out.print(digit); // assuming that digit needs only a single character to print
}
System.out.println();
}
}
Sure, this program is longer than the other ones, but when stepping through it using a debugger, you have all the information about the current state captured in the variables. By looking at the variable values, you can always ask yourself: does it make sense, and do spaces and digits and width fit together?
This program also splits up the total work into two phases. In the first phase, determine what to print and how much, and then just print it.
In every loop the number of blanks before a given number i are maxNumber - i and the times the current number is displayed are i:
for (int i = 1; i <= 5; i++)
{
String blanks = "";
for (int j = 1; j <= 5-i; j++)
{
blanks += " ";
}
String number = "";
for(int k = 1; k <= i; k++)
{
number += i;
}
System.out.print(blanks + number);
System.out.println();
}
I'm trying to create a number grid in Java that would look like this:
789
456
132
public class Test {
public static void main(String[] args) {
//create grid
int [] [] grid = new int [3][3];
grid [0][0] = 7;
grid [1][0] = 8;
grid [2][0] = 9;
grid [0][1] = 4;
grid [1][1] = 5;
grid [2][1] = 6;
grid [0][2] = 1;
grid [1][2] = 2;
grid [2][2] = 3;
int rows = 3;
int columns = 3;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.println(grid[i][j] + " ");
}
System.out.println("");
}
}
}
the result that I'm getting is:
7
4
1
8
5
2
9
6
3
Any suggestions on to where I am going wrong? Many thanks in advance
System.out.println() prints a newline every time. Instead use System.out.print() in the inner loop. Also you need to switch i and j when printing:
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(grid[j][i] + " ");
}
System.out.println("");
}
use System.out.print(grid[j][i] + " "); you need to swap the position ofi and j because your numbers entered are in columns whereas you want them to be printed in rows.
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(grid[j][i] + " ");
}
System.out.println("");
}
output
7 8 9
4 5 6
1 2 3
So i'm having a bit of trouble with my code in returning the sum of the columns in a two dimensional array with rows of different lengths. For example a 2X2 array works perfectly to calculate the sum of the columns. But if I were to have for example a 2X3 array it gives me an out of bounds error. I want it to work for any numbers given by the user for rows and columns not just a fixed number that I said as an example. Can somebody help me resolve this issue? much thanks!
here is my code:
public static void columnSum(int[][]anArray) {
int totalcol = 0;
for(int col =0; col < anArray.length; col++){
totalcol = 0;
for(int row = 0; row < anArray[col].length; row++) {
totalcol += anArray[row][col];
}
System.out.println("Sum of column " + col + " = " + totalcol);
}
}
Your indices are flipped. Your for loops are written for column-major ordering, but your totalizer is written for row-major order. You need to reverse one or the other.
You have a problem in the for loop
for(int row = 0; row < anArray[col].length; row++) {
totalcol += anArray[row][col];
}
If the array is 2X3 then in this for loop when you are using the col = 0 Then anArray[col].length returns value 3. So your row variable can have values 0 - 2 in the for loop. So when the value of row is 2 and the value of column is 0 (as stated earlier), anArray[row][col] will throw an ArrayOutOfBoundException as anArray[2][0] does not exists.
So try out this instead:
for(int row = 0; row < anArray.length; row++) {
totalcol += anArray[row][col];
}
I think this will work.
The question does not specify the order of the array elements. There are two possiblities:
anArray[i][j] represents the element at row i and column j (row-major)
anArray[i][j] represents the element at column i and row j (column-major)
The easier task to solve is finding column sums in a column-major array, or---completely equivalently---row sums in a row-major array. The proposed solution in the question only needs to replace totalcol += anArray[row][col] with totalcol += anArray[col][row] and would already work for this case.
It is a bit more difficult to compute column sums in a row-major array, or---again equivalently---row sums in a column-major array. The rest of this answer shows how to compute column sums for a row-major array. In this case, anArray.length is the number of rows, and anArray[i].length is the number of columns in row i.
In the more usual case where all your rows have the same number of columns, you could do this:
int numrows = anArray.length;
int numcols = (numrows > 0) ? anArray[0].length : 0; // Guard against 0x0 array
for(int col = 0; col < numcols; col++) {
int totalcol = 0;
for(int row = 0; row < numrows; row++) {
totalcol += anArray[row][col];
}
System.out.println("Sum of column " + col + " = " + totalcol);
}
If your rows may each have a different number of columns (as suggested by the question title), you need to:
Determine when there are no more columns to sum over.
When computing the sum of column col, make sure to skip rows that are too short
One way would be:
int numrows = anArray.length;
for(int col = 0; /* not known a priori*/; col++) {
int totalcol = 0;
boolean emptySum = true; // At first, assume no rows are long enough
for(int row = 0; row < numrows; row++) {
if(anArray[row].length <= col ) continue; // Skip short row
emptySum = false; // Mark assumption as wrong
totalcol += anArray[row][col];
}
// Exit the loop if we did not sum anything, i.e. no row had a column with index col
if(emptySum) break;
System.out.println("Sum of column " + col + " = " + totalcol);
}
Instead of using the awkward emptySum flag to quit the loop, you could determine the maximal column length in a preliminary pass:
int numrows = anArray.length;
int maxnumcols = (numrows > 0) ? anArray[0].length : 0; // Guard against 0x0 array
for(int row = 1; row < numrows; row++) {
maxnumcols = Math.max(maxnumcols, anArray[row].length);
}
for(int col = 0; col < maxnumcols; col++) {
int totalcol = 0;
for(int row = 0; row < numrows; row++) {
if(anArray[row].length <= col) continue; // Skip short row
totalcol += anArray[row][col];
}
System.out.println("Sum of column " + col + " = " + totalcol);
}
Finally, if you are allowed to store the sums (instead of immediately outputting them), this would be an even cleaner solution (note the row-major order of iteration, which fits nicely to the row-major order of the array itself):
int numrows = anArray.length;
int maxnumcols = (numrows > 0) ? anArray[0].length : 0; // Guard against 0x0 array
for(int row = 1; row < numrows; row++) {
maxnumcols = Math.max(maxnumcols, anArray[row].length);
}
int[] colsums = new int[maxnumcols]; // In Java, all elements are initialized to zero
for(int row = 0; row < numrows; row++) {
for(int col = 0; col < anArray[row].length; col++) {
colsums[col] += anArray[row][col];
}
}
for(int col = 0; col < colsums.length; col++) {
System.out.println("Sum of column " + col + " = " + colsums[col]);
}
I am trying to print below star pattern
*
***
*****
***
*
I am using below logic to print :
*
***
*****
Code for first half:
int i, j;
for (i = 1; i <= 3; i++) {
for (j = 1; j <= i; j++)
System.out.print("*");
for (j = i - 1; j >= 1; j--)
System.out.print("*");
System.out.println();
}
But still I am not sure about how to print the whole structure.
You just have to write in reverse the loop, to start from the upperBound - 1. See the code bellow:
int numberOfLines = 3;
for (int i = 1; i <= numberOfLines; i++) {
for (int j = 1; j < 2*i; j++){
System.out.print("*");
}
System.out.println();
}
for (int i = numberOfLines - 1; i > 0; i--) {
for (int j = 1; j < 2*i; j++){
System.out.print("*");
}
System.out.println();
}
It will perhaps make sense to go in as simple steps as possible.
First, you need five lines, so
for (i = 1; i <= 5; i++) {
Next, on line i, determine the number of asterisks you are going to place. It is five asterisks on line 3, two less with each step above or below that line.
int len = 5 - Math.abs (i - 3) * 2;
Then, just place them in a single loop:
for (j = 1; j <= len; j++)
System.out.print("*");
And include a newline:
System.out.println();
}
The pattern consist of N * 2 - 1rows. For each row columns are in increasing order till Nth row. After Nth row columns are printed in descending order.
Step by step descriptive logic to print half diamond star pattern.
Input number of columns to print from user. Store it in a variable say N.
Declare a variable as loop counter for each column, say columns = 1.
To iterate through rows, run an outer loop from 1 to N * 2 - 1. The loop structure should look like for(i=1; i<N*2; i++).
To iterate through columns, run an inner loop from 1 to columns. The loop structure should look like for(j=1; j<=columns; j++). Inside this loop print star.
After printing all columns of a row, move to next line.
After inner loop check if(i <= N) then increment columns otherwise decrement by 1.
int columns = 1;
int N = 3;
for (int i = 1; i < N * 2; i++) {
for (int j = 1; j <= columns; j++) {
System.out.print("*");
}
if (i < N) {
/* Increment number of columns per row for upper part */
columns++;
} else {
/* Decrement number of columns per row for lower part */
columns--;
}
/* Move to next line */
System.out.print("\n");
}
Output:
*
**
***
**
*