Why is the result only 81 when I try to use array - java

Thanks for reading my question:
public class Gugudan_array {
public static void main(String[] args) {
for(int i = 2; i<10; i++) {
for(int j = 1; j<10; j++) {
System.out.println(i * j);
}
System.out.println();
}
}
}
In the multiplication table above, result comes correctly from 2-9, however:
public class Gugudan_array {
public static void main(String[] args) {
int[] result = new int[10];
for(int h = 0; h < result.length; h++) {
for(int i = 2; i < 10; i++) {
for(int j = 1; j<10; j++) {
result[h] = (i * j);
}
}
}
for(int a = 0; a < result.length; a++) {
System.out.println(result[a]);
}
}
}
In this code with array, the result comes out only 81.
What have I done wrong?
Thank you!

I'll first explain why your code doesn't work, and then go over a correct solution:
public class Gugudan_array {
public static void main(String[] args) {
int[] result = new int[10];
for(int h = 0; h < result.length; h++) {
for(int i = 2; i < 10; i++) {
for(int j = 1; j<10; j++) {
result[h] = (i * j);
}
}
}
for(int a = 0; a < result.length; a++) {
System.out.println(result[a]);
}
}
}
The main problem lies in this chunk of code:
for(int i = 2; i < 10; i++) {
for(int j = 1; j<10; j++) {
result[h] = (i * j);
}
}
Here, you are constantly overwriting the value of result[h], so that once the loop ends and both i = 9, and j = 9, the code will execute result[h] = 9 * 9 and then continue on to the next h.
My solution:
public class Gugudan_array {
public static void main(String[] args) {
int[] result = new int[10];
for(int i = 2; i < 10; i++) {
for(int j = 1; j<10; j++) {
result[i - 2] = (i * j);
}
}
for(int a = 0; a < result.length; a++) {
System.out.println(result[a]);
}
}
}
Output:
18
27
36
45
54
63
72
81
0
0
First, notice how I completely got rid of the h loop. That is because we can make the index in terms of i. When we determine the first number, when i = 2, we want to store that number in the 0th index of our array. Similarly, when we get our second number, when i = 3, we want to store the result in the 1st index of our array.
To summarize, whenever we calculate a result, we will want to store it in the i - 2th index of our array.
Better Solution using 2D arrays:
int[][] result = new int[8][9];
for(int i = 2; i < 10; i++) {
for(int j = 1; j<10; j++) {
result[i - 2][j - 1] = (i * j);
}
}
for(int a = 0; a < result.length; a++) {
for(int b = 0; b < result[a].length; b++){
System.out.print(result[a][b] + " ");
}
System.out.println();
}
Output:
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
Note: If you want the output to match your original code, change System.out.print(result[a][b] + " "); to System.out.println(result[a][b])
It would make the most sense to store a multiplication table in a 2D array.
This code works by mapping i * j to the [i - 2][j - 1]'th element of the 2D array, so that 2 * 1, will end up in result[0][0]
I hope this made sense! Please let me know if you need any further help or clarification!

You have to increase h variable after all iteration. Here is whole code:
public static void main(String[] args) {
int[] result = new int[10];
for (int h = 0; h < result.length; h++) {
for (int i = 2; i < 10; i++) {
for (int j = 1; j < 10; j++) {
result[h] = (i * j);
if (h < 9) {
h++;
}
}
}
}
for (int a = 0; a < result.length; a++) {
System.out.println(result[a]);
}
}

The issue is that your current setup with 3 nested loops, the outer loop runs 10 times, the middle loop runs 8 times for each other loop, and the inner loop runs 9 times for each middle loop, which gives a total of 10x8x9=720 times... but I suspect you just want 72 results like you show in your first example, so we need to remove the outer loop first for(int h = 0; h < result.length; h++) {.
Now the issue is that we need to store all 72 results but your current array only fits 10 results int[] result = new int[10];, we can solve this with a bigger array:
int[] result = new int[8 * 9]; //72 spaces
Here is a working solution with a long array and a counter that keeps track of where to store the value, note the code comments for extra details:
//Your loops calculate 8 * 9 results, so you need an array with 72 spaces
int[] result = new int[72];
//Use a variable to track the array location
int counter = 0;
//Youn only need two loops
for(int i = 2; i < 10; i++) {
for(int j = 1; j< 10; j++) {
//Save the result in the correct location
result[counter] = (i * j);
//Incriment the counter
counter++;
}
}
//Print the stored results
for(int a = 0; a < result.length; a++) {
System.out.println(result[a]);
}
Some further important reading from the official Java guide on Arrays:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
A better solution would be to use a 2D array.

Related

Java For Loop triangle pattern

Hey I' m trying to create a pattern that's suppose to output multiples of 5 in a pattern like this:
5 10 15 20 25
30 40 45 50
55 60 65
70 75
80
but my output is like this
5 10 15 20 25
30 35 40 45
50 55 60
65 70
75
but when i put asterisks in the print :
*****
****
***
**
*
here's my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int n = 5;
int x =5;
for(int i = n; i>=1; i--){
for(int j = n-1; j>=i; j--){
System.out.print(" ");
}
for(int k = 1; k<=i; k++){
System.out.print(x+" ");
x+=5;
}
System.out.println();
}
}
}
can somebody help me? i spent almost 3 hours trying to figure this out. any help would be appreciated. thanks!
The cleanest way to achieve what you want is to do is by using printf as shown below:
public class Main {
public static void main(String[] args) {
int n = 5;
int x = 5;
for (int i = n; i >= 1; i--) {
for(int j=1;j<n-i+1;j++)
System.out.printf("%3s"," ");
for (int k = 1; k <= i; k++) {
System.out.printf("%3d",x);
x += 5;
}
System.out.println();
}
}
}
Output:
5 10 15 20 25
30 35 40 45
50 55 60
65 70
75
Update:
If you are not comfortable with printf, you can use the following solution:
public class Main {
public static void main(String[] args) {
int n = 5;
int x = 5;
String space=" ";
for (int i = n; i >= 1; i--) {
for(int j=1;j<(n-i)*3;j++)
System.out.print(space);
for (int k = 1; k <= i; k++) {
System.out.print(x+space);
x += 5;
}
System.out.println();
}
}
}
Output:
5 10 15 20 25
30 35 40 45
50 55 60
65 70
75
You write three characters at a time (space, first digit, second digit), so you need to print three spaces to have the correct results.
Basically your same code, but with three spaces int the System.out.print:
for(int i = n; i>=1; i--){
//This is the same loop, but written in a different way.
for(int j = 0; i < n-i; j++){
System.out.print(" "); //THREE SPACES HERE
}
for(int k = 1; k<=i; k++){
System.out.print(x+" ");
x+=5;
}
System.out.println();
}
Now, you are also printing the 5 at the start, which is one digit long, so you need another space before. So you need a conditional structure in order to do this:
//This is the same loop, but written in a different way.
for(int j = 0; i < n-i; j++){
if(j == 0 && x <= 5) //First cycle (remember 5, which is 1 digit)
System.out.print(" "); //TWO SPACES HERE
else
System.out.print(" "); //THREE SPACES HERE
}
Note that this only works with 2 digits numbers so you need to do a similar thing like the one we used with the number five if you're gonna use also 3 or more digits numbers.
I think this exercise is also a good moment to practice with System.out.printf()
Here is how i would do this:
public static void main(String[] args) {
int x = 5;
int n = 35;
int max = calculateTotalNumbers(n) * x; // calculate the highest number
int maxLenght = String.valueOf(max).length(); //calculate the numbers of digits in the highest number
for(int i = n; i>=1; i--){
for (int j = 0; j < n - i; j++) {
//makes sure you will have the same length spaces everywhere
System.out.printf("%1$"+maxLenght+"s ", "");
}
for (int k = 1; k <= i; k++) {
//this formatting will ensure every digit has the same length with padding included. Check out the javadoc of System.out.printf();
System.out.printf("%" + maxLenght + "d ", x);
x += 5;
}
System.out.println();
}
}
// this method will calculate the total number of numbers you will print in the triangle
private static int calculateTotalNumbers(int n) {
if (n <= 0) return 0;
else return (n + calculateTotalNumbers(n -1));
}
public class temp {
public static void main(String[] args) {
int n = 5;
int p = 1;
for (int i = 0; i < n ; i ++){
String curr = "";
for (int j = 0 ; j < n - (n - i); j ++){
curr += " ";
if (j > 0) {
curr += " ";
}
}
for (int j = i; j < n; j ++){
curr += Integer.toString(n * p);
curr += " ";
p += 1;
}
System.out.println(curr);
}
}
}

How do I make my two-dimensional array show horizontally as well as vertically in java?

I'm trying to make a two-dimensional array that generates a random number from 0-50. It works but it doesn't generate a 3 by 5 layout with columns and rows.
I've tried changing around the i and the j and using different variables.
/**
* Constructor for objects of class GenerateLithium
*/
public GenerateLithium()
{
randomGenerator = new Random();
}
public void generateSample()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
tray[i][j] = i * j;
tray[i][j] = grading++;
grading = randomGenerator.nextInt(50);
System.out.print(" ");
}
}
}
public void printTray()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
System.out.println(tray[i][j] + " ");
}
System.out.println("");
}
}
Result Now:
45
22
11
23
1
35
45
43
22
13
15
3
0
16
42
Expected Result:
45
22
11
23
1
35
45
43
22
13
15
3
0
16
42
public void printTray()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
System.out.print(tray[i][j] + "/t ");
}
System.out.println("");
}
}
Replace the first System.out.println with System.out.print inside printTray() method.
You can do this to show output of array 2D as Grid layout:
public void printTray()
{
for (int[] x : tray) {
System.out.println(Arrays.toString(x));
}
}
This is a full GenerateLithium class that prints a 3 x 5 table.
class GenerateLithium{
Random randomGenerator;
int[][] tray = new int[5][3];
int grading;
public GenerateLithium() {
randomGenerator = new Random();
}
public static void main(String args[]) throws UnsupportedEncodingException {
GenerateLithium m = new GenerateLithium();
m.generateSample();
m.printTray();
}
public void generateSample() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
tray[i][j] = i * j;
tray[i][j] = grading++;
grading = randomGenerator.nextInt(50);
}
}
}
public void printTray() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(tray[i][j] + "\t");
}
System.out.println();
}
}
}
Result:
0 8 14
29 33 20
18 37 10
33 21 2
8 45 29

How to define elements in matrix in Java, where in every next row elements increase for some value?

For example I want to make this kind of matrix:
1 1 1 1 1 1
4 4 4 4 4 4
9 9 9 9 9 9
16 16 16 16 16 16
25 25 25 25 25 25
36 36 36 36 36 36
49 49 49 49 49 49
My code so far:
public static void main(String[] args) {
int matrix[][] = new int[6][8];
for (int i = 0; i < matrix.length; ++i) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = i + 1 ;
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
}
}
If you look closely, each element in your result matrix is square of the row number.
Eg.
Row 1 -> Numbers 1
Row 2 -> Numbers 4
Row 3 -> Numbers 9
...
Row 7 -> Numbers 49
and so on...
So you don't need the previous numbers to calculate the new ones.
A simple tweak in your existing code, while populating the matrix, would work:
for (int i = 0; i < matrix.length; ++i) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = (int) Math.pow(i + 1, 2);
}
}
And print the matrix using :
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
public class Matrix {
public static void main(String[] args) {
int matrix[][] = new int[7][8];
for (int i = 0; i < matrix.length; ++i) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = i + 1 ;
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
//Change this line,looking for this?
System.out.print(matrix[i][j]*matrix[i][j] + "\t");
//Describe your specific problem properly
}
System.out.println();
}}
You can use Java.lang.Math.pow() method. But since its only a sqaure function I dont see any harm in using matrix[i][j] = (i+1)*(i+1) ; , inject this code at your 8th line.

Creating a symmetrical 2D array

I've been racking my brains over something that must be incredibly simple, as I've not seen it answered anywhere (or I'm very bad at searching).
I want to create a symmetrical 2D array, filled with random numbers from 1 to 100 inclusive... here is what I've got so far
int n = 3;
int rangeOfWeights = 100;
double[][] array = new double[n][n];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
array[i][j] = rand.nextInt((rangeOfWeights)+1);
}
}
At the moment, this is giving results like:
44 45 32
9 31 53
25 48 74
when actually the kind of result I want is:
0 34 32
34 0 23
32 23 0
As you defined, you're trying to create a 2D array where array[i][j] == array[j][i]. You could a pair of nested loops where one iterates up to the array's size and the other up to the outer array's counter, and in each iteration set the value of the two symmetrical values:
double[][] array = new double[n][n];
for(int i = 0; i < n; i++) {
for(int j = 0; j < i; j++) {
int value = rand.nextInt((rangeOfWeights)+1);
array[i][j] = value;
array[j][i] = value;
}
}

Filling a two dimensional array with integers java

I wanted to write a function which should fill a two dimensional array like this:
1 -- 3 -- 5 -- 7 -- 9
3 -- 5 -- 7 -- 9 -- 11
5 -- 7 -- 9 -- 11 -- 13
7 -- 9 -- 11 -- 13 -- 15
9 -- 11 -- 13 -- 15 -- 17
Here's it what I could come up with ... by all my logic it should work, but obviously I made some mistake:
public class Array {
public static void TwoDimFill(int[] [] array, int start, int inc){
array[0] [0] = start;
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){enter code here
array[i][j+1] = array[i][j] + inc;
}
array [i+1][0] = array[0][i+1];
}
}
public static void main(String[] args){
int[] [] b = new int[5] [5];
TwoDimFill(b, 1, 2);
for (int x = 0; x < b.length; x++){
for (int y = 0; y<b[x].length; y++){
TextIO.put(b[x][y]+"\t");
}
TextIO.putln();
}
}
By the way: This TextIO.class is something we use for printing, compareable to system.out ...
Edit: Answered! Thank you a lot guys, you're great!
i+1 and j+1 will be out of bounds because you loop until < length. Change it to < length -1.
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length -1; j++){
array[i][j+1] = array[i][j] + inc;
}
if (i < array.length -1)
array [i+1][0] = array[0][i+1];
}
EDIT: As pointed out on comments, the last output line was incorrect. Variable i can be looped until < length, but it must be verified for the last line that the index won't get out of bounds. Corrected the code above.
There is an excess number of operations you are doing. There is a much cleaner, simpler and faster solution. Sometimes a different approach can solve the problem better.
for (int i = 0; i < array.length; i++)
for (int j = 0; j < array[i].length; j++)
array[i][j]=((i+j)<<1)+1;
You need to check if the index is out of bounds before executing the last line in your loop, as well as only making your inner loop iterate up to length-1 (since indexes for arrays in Java start at 0 and end at 1 less than their length):
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[i].length - 1; j++) {
array[i][j + 1] = array[i][j] + inc;
}
if(i + 1 < array.length) {
array[i + 1][0] = array[0][i + 1];
}
}
This produces:
1 3 5 7 9
3 5 7 9 11
5 7 9 11 13
7 9 11 13 15
9 11 13 15 17
Note that simply clipping the outer loop to array.length-1 doesn't work (since in this case you still want the first part of the loop to execute), you'd end up with the following:
1 3 5 7 9
3 5 7 9 11
5 7 9 11 13
7 9 11 13 15
9 0 0 0 0
Bolding is mine, note the last line is obviously incorrect.
This is wrong because of array[i][j+1]. If j is the last position j+1 doesn't exist. You can try this:
public static void TwoDimFill(int[] [] array, int start, int inc){
int aux = 0;
for(int i = 0; i < array.length; i++) {
aux = start;
for(int j = 0; j < array[i].length; j++) {
array[i][j] = aux;
aux += inc;
}
start += inc;
}
}
You can do this really simply, use the following
public class TestClass {
public static void main(String args[]) {
int[][] temp = new int[5][5];
int[][] output = fill2dim(temp,1,2);
for (int i = 0; i < output.length; i++) {
System.out.println(java.util.Arrays.toString(output[i]));
}
}
public static int[][] fill2dim(int[][] arr, int start, int inc) {
int[][] output = new int[arr.length][arr[0].length];
for (int i = 0;i<arr.length;i++) {
for (int j = i;j<arr[0].length;j++) {
output[i][j] = (i+j)*inc+start;
output[j][i] = (i+j)*inc+start;
}
}
return output;
}
}
You can remove some loops by just considering the upper triangular matrix, since the lower triangular matrix will be a reflection of the upper triangle about the diagonal

Categories