Java multi-dimensional arrays - a question about system output - java

Would anyone please explain the output showm at the bottom for this code. I am somewhat confused about this part and understanding what is stored in doc after execution...
doc[a][b] = a + b;
public class doc
{
public static void main(String[] args)
{
int b = 0;
int [][] doc = new int [3][3];
int a;
while (b<3)
{
for(a=2; a >=0; a--)
doc[a][b] = a + b;
++b;
}
int j;
for (int i=0; i<doc.length; i++) {
for (j=0; j<doc[i].length; j++) {
System.out.println(" " + doc[i][j]); }
System.out.println("");
}
}
}
0
1
2
1
2
3
2
3
4
The output is above.
Thank you.

The array will look like the following
0 1 2
1 2 3
2 3 4
All it is doing is going through and printing out each row in succession. In the for loop
for (int i=0; i<doc.length; i++) {
for (j=0; j<doc[i].length; j++) {
System.out.println(" " + doc[i][j]); }
System.out.println("");
}
i represents the row number and j represents the column number so it says go to row 0 and print out column 1, the col 2, then col 3. Now go to row 1 and print col 1, col 2 and col 3 and so forth with row 2.

Related

Generate a number-pattern in Java beginning with different numbers

I am preparing for my exam from programming. And I am stuck on this task, I understand logic of patterns ( at least I think so ) but I can't figure out how to solve this.
Output for input a = 6 needs to be like :
012345
123456
234567
345678
456789
567890
Output for input a = 3 needs to be like :
012
123
234
Output for input a = 4 needs to be like :
0123
1234
2345
3456
But I'm getting this :
0 1 2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
Here's my code:
for (int i = 0; i <= a; i++) {
for (int j = i; j < a; j++) {
System.out.print(j + " ");
}
System.out.println();
}
You need to make these changes to get the required output:
Termination conditions of the outer for loop should be i < a;
Termination conditions of the inner for loop should be j < a + i;
The number you're printing should be not j but j % 10 to satisfy the data sample you've provided (for input a=6 it prints 0 as the last number on the very last line instead of 10, that means we need not j, but only its rightmost digit which is the remainder of division by 10).
That's how it can be fixed:
public static void printNumbers(int a) {
for (int i = 0; i < a; i++) {
for (int j = i; j < a + i; j++) {
System.out.print(j % 10 + " ");
}
System.out.println();
}
}
Observations:
Since it is a 2 dimensional output, we will need 2 loops ( one inside the other ).
Also, the starting point for each line is the value from which the last line starts +1 .
If the value crosses 10, then we will keep the unit digit value only ( like in the last line). ( therefore we use modulus operator % that helps to extract the unit digit)
Code :
class Main {
public static void main(String[] args) {
int n = 6;
pattern(n);
}
private static void pattern(int n) {
int k = 0;
for (int i = 0; i < n; i++) {
for (int j = k; j < k + n; j++) {
System.out.print(j % 10);
}
k = i + 1;
System.out.println();
}
}
}
and the answer is :
012345
123456
234567
345678
456789
567890

I was trying to print the spiral order matrix as output for a given matrix of numbers, but the output result isn't complete. What is causing this?

I was trying to print the spiral order matrix as output for a given matrix of numbers, all seemed fine until I tried to print the output, the code prints the input till the first spiral loop but stops after printing the second loop for the first step. I am confused, what is my mistake.
edit - the loop has to go clockwise.
import java.util.*;
public class SpiralArray{
public static void main (String [] args){
System.out.println("Enter the size of the array");
//Dimensions of array
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
int c = sc.nextInt();
int [][] spiral = new int [r][c];
// elements of array
for (int i = 0; i < r; i++){
for (int j = 0; j < c; j++){
spiral [i][j] = sc.nextInt();
}
}
int row_start = 0;
int row_end = r-1;
int column_start = 0;
int column_end = c-1;
//printing spiral order matrix
while( row_start <= row_end && column_start <= column_end){
//1
for (int col = column_start; col <= column_end; col++){
System.out.print(spiral[row_start][col] + " ");
}
row_start++;
//2
for (int row = row_start; row <= row_end; row++){
System.out.print(spiral[row][column_end] + " ");
}
column_end--;
//3
for (int col = column_end; col >= column_start; col--){
System.out.print(spiral[row_end][col] + " ");
}
row_end--;
//4
for (int row = row_end; row >= row_start; row--){
System.out.print(spiral[row][column_start] + " ");
}
column_start++;
System.out.println();
}
}
}
Output obtained from the code -
Enter the size of the array
3 4
1 2 3 4
5 5 6 7
8 9 10 1
1 2 3 4 7 1 10 9 8 5
5 6 5
edit
expected output
1 2 3 4 7 1 10 9 8 5
5 6

How to create a matrix using a 2D array

I am trying to create a 6x3 matrix that increases by one each time as you iterate over the column first and the row second.
This is the code, which I currently have:
public static void main(String[] arg) {
int[][] mat1 = new int[6][3];
for(int i = 1; i < mat1.length; i++) {
for(int j = 0; j < mat1[i].length; j++) {
mat1[i][j] = i + j;
System.out.print(mat1[i][j] + " ");
}
System.out.println();
}
}
Right now I am getting the output:
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
The desired output is:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
How would I go about doing this?
You want to generate a "sequence" that counts from 0, 1, 2, .. 17.
Your problem is that i+j doesn't generate that sequence.
Therefore:
mat1[i][j] = i + j;
is simply not counting up. A much simpler solution would be this:
mat1[i][j] = overallCounter++;
( and that overallCounter is declared int overallCounter = 0 before the outer for loop ).
side note: and as the comment correctly states: i should start at 0, too. Arrays are 0-based in Java!
The output you get is correct:
On the first iteration, i = 1 and j = 0, so i+j = 1
On the 4th iteration i = 2 and j = 0, so i+j = 2
On the 7th iteration i = 3 and j = 0, so i+j = 3
here is on of the solution for your problem
public static void main(String[] arg) {
int[][] mat1 = new int[6][3];
int counter = 1;
for(int i = 0; i < mat1.length; i++) {
for(int j = 0; j < mat1[i].length; j++) {
mat1[i][j] = counter;
counter++;
System.out.print(mat1[i][j] + " ");
}
System.out.println();
}
}

How to display first column and row only?

I have created a multiplication table. However, it cannot display the first row and column with my code. Is this even achievable via loop? Herr is my code:
int a;
int b;
for (a=1; a<=3; a++)
{
for (b=1; b<=3; b++)
{
System.out.print(a*b + " ");
}
System.out.println();
}
The output of this code is:
1 2 3
2 4 6
3 6 9
However, i want the 123 on a row and column to display only. Is this achievable?
Desired output:
1 2 3
2
3
A basic approach is to know where your outer loop is at and print accordingly to your desired result.
public class StackOverflow {
public static void main(String[] args) {
int a;
int b;
for (a=1; a<=3; a++)
{
// Only print the first row
if (a == 1) {
for (b=1; b<=3; b++)
{
System.out.print(a*b + " ");
}
// Ends the first row
System.out.println("");
} else {
// Prints the rest of the first column
System.out.println(a);
}
}
}
}
Result:
1 2 3
2
3
UPDATE
If I understand your comment, here's an approach with just one loop. It assumes that the size of the row will equal the size of the column. This means that the number of digits you'll display will be an odd number (rowColLength * 2 - 1) which makes the first digit a pivot point.
public class StackOverflow {
public static void main(String[] args) {
int a = 0;
int rowColLength = 3;
int numberOfDigits = rowColLength * 2 - 1;
for (int i = 0; i < numberOfDigits; i++) {
if (i < rowColLength) {
// Prints the first row
System.out.print(++a + " ");
} else if (i == rowColLength){
// Decrements the last number from the first row
// to continue the column count for printing
System.out.print("\r\n" + --a);
} else {
// Prints the rest of the column
System.out.print("\r\n" + ++a);
}
}
}
}
Result:
1 2 3
2
3
I think you want the upper bounds to be limited.
Better readable would be:
int rows = 3; // 1?
int columns = 10; // 1?
for (int row = 1; row <= rows; ++row) {
for (int column = 1; column <= columns; ++column) {
System.out.printf("%3d", row * column);
}
System.out.println();
}
The printf prints digits, padded to the left upto 3 positions with spaces.
If you want a header row and column à la Excel:
// Header row:
System.out.print("AxB ");
for (int column = 1; column <= columns; ++column) {
System.out.printf("%3d", column);
}
System.out.println();
System.out.print("---|");
for (int column = 1; column <= columns; ++column) {
System.out.print("---");
}
System.out.println();
// Data rows
for (int row = 1; row <= rows; ++row) {
System.out.printf("%3d|", row); // Column header
for (int column = 1; column <= columns; ++column) {
System.out.printf("%3d", row * column);
}
System.out.println();
}
Print header and columns labels in 2 different loops:
int a;
int b;
// Print header label
for (b=1; b<=3; b++) {
System.out.print(b + " ");
}
System.out.println();
// Print column label
for (b=2; b<=3; b++) {
System.out.println(b);
}
The output:
1 2 3
2
3
Several possibilities, you could for example save the result to a variable and not print it if bigger than 3.
int temp = a*b
if (temp < 4){
System.out.print(temp);
else {
System.out.print(" ");
}

How to zigzag numbers in floyd's triangle pattern?

I have found a way for zigzag matrix but I am willing to find same as clean code for triangle pattern.
Example:
input = 3
Output:
1
32
456
I already coded a numbered matrix code here:
int k=0;
int t=1;
int n=4;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
k+=t;
System.out.print(k);
}
k=k+n+t;
t=-t;
System.out.println();
}
Output:
1234
8765
9101112
16151413
int n = 6;
int num = 0;
int step = 1;
for (int i = 1; i <= n; i++) {
// num : (i² - i + 2)/2 .. same + i - 1
for (int j = 0; j < i; j++) {
num += step;
System.out.print(num);
System.out.print(' ');
}
num += i + (1 + 3*step)/2;
step = -step; // zig resp. zag
System.out.println();
}
Helpful was numbering i as row with exactly i elements.
Yielding
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
21 20 19 18 17 16
The problem was that every row i of i numbers has a lowest value (i² - i + 2)/2,
and for the next zigzagging number one needs to consider the following step.
From the last row number to the first row number of the next line has two cases:
step -1
step 1
Both formulas of both cases can be unified by the step.
step i num
+ 1 1 -> 4 += i + 2
- 2 2 -> 3 += i - 1
+ 3 6 -> 11 += i + 2
- 4 7 -> 10 += i - 1
The following will work:
public static void zigZag(int rows) {
int current = 1;
int increment = 1;
for (int row = 1; row <= rows; row++) {
int width = row + current;
for (int element = current; element < width; element++) {
System.out.print(current);
current+=increment;
}
System.out.println();
current += row + 0.5 - (0.5*increment);
increment = -increment;
}
}
Edit: just a note because I suspect your question might be homework motivated, so it might help if you can understand what's going on instead of just copy-pasting.
All that really needed to change was to use the external loop variable (the one that was originally creating your matrix square, which I've called row) in the inner loop which prints the individual elements of the row.
This is then used to calculate the first element of the next row. The increment value does the same as it does in your original, but now it can also be used to have the zig-zag pattern go up in integers other than 1.
Starting from the top of the triangle (1) will be row 1, all subsequent even rows are printed in reverse. Knowing that you can try something like this:
public class StackOverflow {
public static void main(String[] args) {
int triangleSize = 5;
int counter = 1;
int rowSize = 1;
for (int i = 1; i <= triangleSize; i++) {
if (i % 2 == 0) {
// Reverse number sequence
int reverseCounter = counter + rowSize - 1;
for (int j = 0; j < rowSize; j++) {
System.out.print(reverseCounter--);
counter++;
}
} else {
for (int j = 0; j < rowSize; j++) {
System.out.print(counter++);
}
}
System.out.println("");
rowSize++;
}
}
}
Keep track what row you're on (rowSize) and what value you're on (counter). When you're on an even row you have to start with the highest value that row will have and count backwards from it, but still increment your normal counter (int reverseCounter = counter + rowSize + 1).
Result:
1
32
456
10987
1112131415
Try this I coded it for you:
public class TriangleNum{
public static void main(String[] args) {
getTringle(5);
}
public static void getTringle(int j){
for (int i =0; i<j;i++) {
System.out.print(i+ "\r" );
for (int k =0; k<i;k++) {
System.out.print(k+ "\t" );
}
}
}
}
//Using C Language
#include<stdio.h>
int main(){
int n,count=1,k=1;
printf("Enter number of lines:\n");
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
if(i%2==1){printf("%d",count);count++;}
else{printf("%d",count);count--;}}
count=count+k;
if(i%2==1){k=k+2;}
printf("\n");
}
return 0;
}

Categories

Resources