Java number triangle in decreasing order - java

I need to produce a triangle like:
6
55
444
3333
22222
111111
This is my code:
for (int row = 1; row <= size+1; row++) {
for (int col = 1; col <= size+1 - row ; col++)
{
System.out.print(row);
}
System.out.println();
}
which produces an upside down triangle.

This produces the desired results:
for (int row = 1; row <= size; row++) {
for (int col = 1; col <= row; col++) {
System.out.print((size - row + 1) + "\t");
}
System.out.println();
}
You'll need to remove the tab character though to get the results posted above.

This will help
int num=size;
for(int i=1;i<=size;i++){
for(int j=1;j<=i;j++){
System.out.print(num);
}
System.out.println();
num--;
}

Related

How to make Nested for loop pattern

how to make following pattern in java using nested for loop
1
21
321
4321
54321
654321
I was trying it with this one.
for (int r = 1; r <= 6; r++) {
for (int s = 6; s > row; s--) {
System.out.print(" ");
}
for (int c = 1; c<=r; c++) {
System.out.print(c);
}
System.out.println("");
}
but output of this code was:
1
12
123
1234
12345
123456
expected result:
1
21
321
4321
54321
654321
If you want to start at 6 and go down, then you need to start at row in this loop:
for (int col = 1; col<=row; col++) {
System.out.print(col);
}
Change it to:
for (int col = row; col > 0; col--) {
System.out.print(col);
}
Only two nested loops are enough to achieve that pattern you asked for
for (int row = 1; row < 7; row++) {// for loop for rows
for (int spaces = 6; spaces > 0; spaces--) {
if(spaces> row)
System.out.print(" ");
else
System.out.print(spaces);
}
System.out.println("");
}

How to print the right number of asterix in columns and rows?

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

Need some help using Java with matrix

I am studying and have a little trouble.
I have to build matrix like this on the picture
Matrix
But i can't put a stars in that places.
public static void main(String[] args) {
int[][] twoD = new int[5][5];
int i, j, k = 1;
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++) {
twoD[i][j] = k;
k++;
}
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++)
System.out.print(twoD[i][j] + " ");
System.out.print("\n");
}
}
Here is my code, please help to find
You can take the answer from a previous question and slightly modify it like so
public static void printCross(int size, char display)
{
int count = 0; //add a counter
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
count++; //increment each index we come across
if (row == col || row + col == size - 1) {
//print out the X using teh given display character
System.out.print(String.format("%-3s", display));
} else {
//print out the current count
System.out.print(String.format("%-3s", count));
}
}
System.out.println();
}
}
Output
X 2 3 4 X
6 X 8 X 10
11 12 X 14 15
16 X 18 X 20
X 22 23 24 X
I have found the easiest way i think.
public static void main(String args[]){
String[][] Matrix = { {" *"," 2"," 3"," 4"," *"} , {" 6"," *"," 8"," *","10"} , {"11","12"," *","14","15"} , {"16"," *","18"," *","20"} , {" *","22","23","24"," *"}};
for(int i=0; i< Matrix.length; i++){
for(int j=0;j < Matrix.length; j++){
System.out.print(Matrix[i][j]+" ");
}
System.out.println("");
}
}

Finding the sum of columns in a Two Dimensional Array with rows of different lengths

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

Display lottery winners

I created a lottery program to randomly generate 3 numbers between 0-9 and then randomly generate the 3 winning numbers. I need help on how to make the program display the winners (if there are some) and display the number of how many won the lottery.
So something like:
Winners:
Person1
person5
Number of winners: 2
Here is my program
import java.util.Random;
public class TwoDArray
{
public static void main(String[] args)
{
int[][] table = new int[50][3];
int[][] win = new int[1][3];
Random rand = new Random();
int i = 1;
// Load the table with values
for (int row=0; row < table.length; row++)
for (int col=0; col < table[row].length; col++)
table[row][col] = rand.nextInt(7-0 +1)+0 + col;
// Load the winning Values
for (int row=0; row < win.length; row++)
for(int col=0; col < win[row].length; col++)
win[row][col] = rand.nextInt(7-0 +1)+0 + col;
// Print the table of People
for (int row=0; row < table.length; row++)
{
System.out.print("Person" + i++ +":\t");
for (int col=0; col < table[row].length; col++)
System.out.print(table[row][col] + "\t");
System.out.println();
}
//Print the Winning Numbers
for (int row=0; row < win.length; row++)
{
System.out.print("\nThe winning numbers are:\t");
for(int col=0; col < win[row].length; col++)
System.out.print(win[row][col] + "\t");
System.out.println();
}
}
}
You want another for loop. Something like:
int counter = 0;
for (int i =0; i < table.length; i++){
if (table[i][0] == win[0][0] && table[i][1] == win[0][1] && table[i][2] == win[0][2])
{
counter++;
System.out.println("Person " + i);
}
}
System.out.println("There were " + counter + " winners.");

Categories

Resources