Below is the code I'm messing with, pretty basic. I was looking for a way to print only specific elements of the array. For example, if I wanted to print only the element at index 1 of array[i], as well as the element at index 1 of array[j] when its value is 1. See below for the output I'm looking for.
Expected output :
1 3 5
4
7 8 9
Code:
public class multiDimensional {
public static void main(String args[]){
int arr[][] = {{1,3,5}, {2,4,6}, {7,8,9}};
for(int i=0; i < 3; i++){
for(int j=0; j < 3; j++){
System.out.print(arr[i][j]+" ");
//System.out.println();
}
System.out.println();
}
}
}
Actual output :
1 3 5
2 4 6
7 8 9
You can produce your expected output by using an if statement to decide when to write a value:
public static void main(String args[]){
int arr[][] = {{1,3,5}, {2,4,6}, {7,8,9}};
for(int i=0; i < 3; i++){
for(int j=0; j < 3; j++){
if (i == 0 // in the first row
|| i == 2 // in the last row
|| j == 1) { // in the middle column of the middle row
System.out.print(arr[i][j]+" ");
} else {
System.out.print(" "); // this is here to keep the spacing right
}
//System.out.println();
}
System.out.println();
}
}
Note: There are many other ways of coding this, however the approach I am showing is merely to demonstrate how the if statement works.
Related
I am trying to print pascal's triangle using 2D int array
And printing 2D array in below way
public static void pascal (int n)
{
int[][] pascalArray = new int[n][n];
// Code here
}
printArray(pascalArray);
public static void printArray(int[][] array)
{
for (int i = 0; i < array.length; i++)
{
for(int j=0; j<array[i].length;j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println();
}
For n =4
I am getting below output
Enter rows in the Pascal's triangle (or 0 to quit): 4
1 0 0 0
1 1 0 0
1 2 1 0
1 3 3 1
Now I want white-space instead of zero or an isosceles triangle format for pretty print
Is that possible in for 2D int array
or can we change 2D int array into some string array in printArray method and achieve the same?
I tried system.out.format but some how I am unable to get the output because of int 2D array
If you know you want a triangle, and you know the array is square, you could simply change the upper bound of the inner loop.
for (int i = 0; i < array.length; i++)
{
for(int j=0; j<=i; j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println();
}
You may just add the instruction that I added below. It prints only if the value in the array is not equal to "0". If it's a String array, use the equals() method
for (int i = 0; i < array.length; i++)
{
for(int j=0; j<array[i].length;j++)
{
if (array[i][j] != 0) System.out.print(array[i][j] + " ");
}
System.out.println();
}
Here is the series :
12345
22345
33345
44445
I tried to solve this but it is not coming correct...
Here is the code :
class q14
{
public static void main ( )
{
int i,j,k;
for (i=1;i<=5;i++)
{
for (j=i;j<=5;j++)
{
for (k=1;k<=i;k++)
{
System.out.print (i + " ");
}
System.out.print (j + " ");
}
System.out.println();
}
}
}
The following block should generate the series as you described it.
int numberOfLines = 4;
int numberOfDigitsPerLine = 5;
for (int i=1; i<numberOfLines+1; i++){
for(int j=1; j<=numberOfDigitsPerLine; j++) {
if(j>=i) {
System.out.print(j);
} else {
System.out.print(i);
}
}
System.out.println();
}
Change numberOfLines and numberOfDigitsPerLine as necessary.
Elaboration:
First you must analyze the series, by the looks of it the first number starts with 1 and goes onward for 5 digits, the second line goes along 5 digits as well up to 5 as previously but it replaces the first digit with 2.
Moving down the numbers we can see a pattern of which the N-th number will have N amount of N digits followed by consecutive digits up to the number 5.
So in my code above I chose max N to be 4 as you described it, and the numbers go up to 5, these are represented by the variables numberOfLines and numberOfDigitsPerLine respectively.
The block itself checks what is N at that point (in my block it is represented by i) and then proceeds to go towards the max number 5, this is done within the j for loop. If j is larger or equal to N then we print j, otherwise we haven't finished printing all of the N's yet so we print N instead.
Here it is:
for (int i = 1; i <= 5; i++)
{
for(int k = 1; k <= i;k++)
System.out.print(i);
for (int j = i + 1; j <= 5; j++)
System.out.print(j);
System.out.print("\n");
}
You dont need a third loop for your series
for (int j=1;j<=5;j++) {
for (int k=1;k<=5;k++){
if(k<=j)
System.out.print (j + " ");
else
System.out.print (k + " ");
}
System.out.println();
}
output
1 2 3 4 5
2 2 3 4 5
3 3 3 4 5
4 4 4 4 5
5 5 5 5 5
Demo
Try this:
for(int i=1;i<=4;i++)
{
for(int j = 1; j<=5;j++)
{
if(i>j)
{
for(int x= 1 ; x<=i;x++)
{
System.out.print(i);
j++;
}
}
System.out.print(j);
}
System.out.println("\n");
}
public class testing
{
public void show() {
int num = 0;
int n = 5;
for (int i=1; i<n; i++) {
for (int j=0; j<i; j++) {
System.out.print(num++);
System.out.print(" ");
}
System.out.println(" ");
}
}
}
This question came up in one of our previous exams and I don't understand it. The answer is
0
1 2
3 4 5
6 7 8 9
But I have no clue how they got it. I kind of understand the 2nd to 4th line but have no clue how they got 0 on the first line. Any explanation would be highly appreciated, thanks!
but have no clue how they got 0 on the first line ?
int num = 0; --> it is 0 initially
For the first iteration your inner loop executes only 1 time
for (int i=1; i<n; i++) {
for (int j=0; j<i; j++) { ---> for(int j=0;j<1;j++) // for 1st time
So that is why the below line
System.out.print(num++); //printed 0
Note : there is a tool known as debugger , Use it !!
Maybe the following amended code could help to understand
int num = 0;
int n = 5;
for (int i=1; i<n; i++) { // loop from 0 to 4
System.out.printf("num=%d i=%d : ", num, i);
for (int j=0; j<i; j++) { // loop from 0 to i
System.out.print(num++); // print num then increment num
System.out.print(" ");
}
System.out.println(" ");
}
output
num=0 i=1 : 0
num=1 i=2 : 1 2
num=3 i=3 : 3 4 5
num=6 i=4 : 6 7 8 9
I believe your problem lies in this line
System.out.print(num++);
in a more verbose way it does the following
System.out.print(num);
num = num + 1;
I need to write a program that will take a number n from the user and create an nxn matrix that counts up, then I need to transpose it. I've tried multiple methods of coding, but nothing displays correctly.
import java.util.Scanner;
public class SquareMatrix {
public static void main(String[] args)
{
//Variables
int size;
int value;
//Scanner
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Prompt
System.out.println("Enter the size of the Square Matrix: ");
size = input.nextInt();
for(int i=1; i<=size; i++) {
System.out.println();
for(int j=0; j<size; j++) {
value = i+j;
System.out.print(value);
}
}
}
}
The result I'm currently getting is:
Enter the size of the Square Matrix:
3
123
234
345
I need it to look more like this:
Enter the Size of the Square Matrix:
3
Square Matrix:
1 2 3
4 5 6
7 8 9
Transpose:
1 4 7
2 5 8
3 6 9
The nxn matrix counting up is
for(int i=0; i<size; i++) {
System.out.println();
for(int j=1; j<=size; j++) {
value = j + i*size;
System.out.print(value);
}
}
The transponse is
for(int i=1; i<=size; i++) {
System.out.println();
for(int j=0; j<size; j++) {
value = j*size + i;
System.out.print(value);
}
}
I wrote a code that does exactly what you need. It may seem overcomplicated but i think it grasp the idea that you would do with pencil and paper. You need to put the scanning user input part in though.
int n=10;
int[][] matrix =new int[n][n]; // a 2D array as one would imagine a matrix
int num=0;
int temp=0;// used in transposing
//initializing the arrays of the second dimension
for (int init=0;init<n;init++){
matrix[init]=new int[n];
}
System.out.println("filling and printing matrix");
for (int fill_row=0;fill_row<n;fill_row++){
for(int columns=0;columns<n;columns++){
matrix[fill_row][columns]=++num;
if(columns==n-1){
System.out.println(Arrays.toString(matrix[fill_row]));
}
}
}
System.out.println("Transposed matrix");
for (int transp_row=0;transp_row<n;transp_row++){
for(int columns=transp_row;columns<n;columns++){
//store actual value to temp,
temp=matrix[transp_row][columns];
//by switching the order of the indicies assign new value to current position
matrix[transp_row][columns]=matrix[columns][transp_row];
//assgin temp value to what we used as replacement
matrix[columns][transp_row]=temp;
if(columns==n-1){
System.out.println(Arrays.toString(matrix[transp_row])); // print each rows of the array
}
}
}
}
I hope it helps.
I happened to appear for a test and got the following as question. I am unable to figure out how to proceed. The scenario is to write a java program that prints the following with respective N. If suppose N=3, it must have 2*N rows and output must be,
1
2*3
4*5*6
4*5*6
2*3
1
Output must consist only numbers and asterisk. N varies between 0 to 100. Also, given
public static void main(String[] args){
int rows=2;
mirrorTriangle(rows);
}
public void mirrorTriangle(int n){
//Logic
}
I don't understand why is that rows declared as 2 if rows are supposed to be varying with N. Please explain the logic.
Please find the solution to your problem, with explanation comments.
public static void main(String[] args) throws Exception
{
// initialize n
int n = 4;
// initialize x to 1 from where our printing will start.
int x = 1;
/* We will store our generated numbers in an array.
* For example, the array after we generate
* the numbers would look like:
* [1,0,0,
2,3,0,
4,5,6,
4,5,6,
2,3,0,
1,0,0]
*
* When n = 3, there are going to be 3*2 i.e, n*2 rows.
* in our case 6 rows.
* visualize with the above values.
* The first n/2 rows will be the numbers we print,
* the next n/2 will be the mirror image of the first n/2 rows.
* no. of columns in each row will be equal to n, in our example:3
*/
int arr[][] = new int[n*2][n];
/*
* Start populating the matrix
* Each row will contain number of elements eaual to the row number,
* so 1st row -> 1 element, 2nd - > 2,.. and so on.
*/
for(int row=0;row<n;row++)
{
int col = 0;
while(col < row+1)
{
arr[row][col] = arr[n*2-row-1][col] = x++;
col++;
}
}
/*
* Now our task is just to read out the array.
* The tricky part is adding the astricks.
* We notice that row1 will have 1-1 asticks, row2 -> 2-1 astricks ,.. and so on.
* So in between the numbers while reading out,
* for each row we maintain the number of astricks.
*/
for(int i=0;i<arr.length;i++)
{
StringBuilder build = new StringBuilder();
for(int j=0;j<arr[i].length;j++)
{
if(arr[i][j] > 0)
{
build.append((arr[i][j])).append("*");
}
}
System.out.print(build.delete(build.length()-1,build.length()).toString());
System.out.println();
}
}
o:p for n=4:
1
2*3
4*5*6
7*8*9*10
7*8*9*10
4*5*6
2*3
1
def N = 3
def i = 0
def j = 0
int[][] numbers = new int[N][]
// Generate, print, and store numbers
while( i < numbers.length ){
numbers[i] = new int[i+1]
j = 0
while( j < numbers[i].length ){
numbers[i][j] = j+1
++j
print j
}
println ""
i++
}
// Print them again, in reverse order
i = numbers.length - 1
while( i >= 0 ){
j = 0
while( j < numbers[i].length ){
print numbers[i][j]
j++
}
println ""
i--
}
Output:
1
12
123
123
12
1
The code is pretty self-explanatory. You need just N rows but print 2N because, wait for it ... symmetry. If you have 6 rows, first 3 are new while the other 3 are just mirrored images so why waste the memory space when you can just print them again?
Is there an explicit requirement for recursion? It is implied by the structure of the problem not mentioned anywhere.
int rows=2 is an example probably, for the purposes of the problem you can't do anything 'smart' like using pointers ...
I will also assume that you are not permitted to use values '> 100' so that you can overload the meaning of the n value - same goes for 2's complement.
If you allow for looping, as a substitute for recursion you can generate the triangle without having to save state outside of the stack:
public static void main(String[] args){
int rows=3;
mirrorTriangle(rows);
}
public static void mirrorTriangle(int n){
for (int i = 0 ; i < n + 1 ; i++) {
renderLine(i);
}
for (int i = n ; i > 0 ; i--) {
renderLine(i);
}
}
private static void renderLine(int n) {
int j = n * (n - 1) / 2 + 1;
int k = j + n;
while (j < k) {
System.out.print(j);
j++;
if (j < k) System.out.print('*');
}
System.out.println();
}
Try this fresh code:
public class String4 {
public static void main(String[] args) {
int rows = 3;
mirrorTriangle(rows);
}
private static void mirrorTriangle(int rows) {
for(int i=1;i<=rows;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(i);
if(j>0&&j<i)
System.out.print("*");
}
System.out.println();
}
for(int k=rows;k>0;k--)
{
for(int l=1;l<=k;l++)
{
System.out.print(k);
if(l>0&&l<k)
System.out.print("*");
}
System.out.println();
}
}
}
Output:
1
2*2
3*3*3
3*3*3
2*2
1
I think this is a better and simple solution than the chosen one.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter limit");
int limit = s.nextInt();
int start[] = new int[limit];
int v = 1;
for (int i=1; i<=limit; i++) {
start[i-1] = v;
for (int j=1; j<=i; j++) {
System.out.print(v++);
if(j==i)
continue;
System.out.print("*");
}
System.out.print("\n");
}
for (int i=limit-1; i>=0; i--) {
v=start[i];
for (int j=i; j>=0; j--) {
System.out.print(v++);
if(j==0)
continue;
System.out.print("*");
}
System.out.print("\n");
}
}