I need help, I got a problem with this matrix, I need to have it in this way:
1 2 3 4 = 10
2 4 6 8 = 20
3 6 9 12 = 30
4 8 12 16 = 40
But I have it in this way:
1 2 3 4 1
2 4 6 8 2
3 6 9 12 3
4 8 12 16 4
I dont know how can we do that, I intent but nothing
This is my code:
public class Matrix {
public static void main(String args[]) {
int mult = 4;
for (int i = 1; i <= mult; i++) {
// System.out.println();
for (int j = 1; j <= mult; j++) {
int operacion = i * j;
int suma = 0;
suma = operacion + suma;
System.out.print(operacion + " ");
}
int sum = 0;
sum = i + sum;
System.out.println(sum);
}
}
}
bye
When you do this:
for (int j = 1; j <= mult; j++) {
int operacion = i * j;
int suma = 0;
suma = operacion + suma;
suma is always equal to operacion, because you set it to 0 every time and then add operacion.
You want to do this:
int suma = 0;
for (int j = 1; j <= mult; j++) {
int operacion = i * j;
suma += operacion;
Put int sum = 0 outside the second for loop.
int suma = 0;
for (int i = 1; i <= mult; i++) {
// System.out.println();
suma =0;
for (int j = 1; j <= mult; j++) {
int operacion = i * j;
suma = operacion + suma;
System.out.print(operacion + " ");
}
System.out.println(suma);
}
You should take a look to String.format() or PrintStream.printf(). I think others allready helped you with the sum-problem. So try to print the values out like this:
for (int i = 0; i < 4; i++)
{
int[] values = new int[4];
int sum = 0;
for (int j = 0; j < 4; j++)
{
values[i] = (i+1) * (j+1);
sum += values[i];
}
System.out.printf("%-4d%-4d%-4d%-4d = %d\n", values[0], values[1], values[2], values[3], sum);
}
Try also to remove all the minus signs (-) from the last line and see what you like the most.
You are resetting sum to 0 just before you use it. You probably want for sum to be reset before your inner loop, added to inside your inner loop and printed outside your inner loop.
Also for your final println, print (" = " + sum) instead of just sum.
Trying not to actually correct your code since you mentioned this is an exercise (homework)--and thank you for tagging it. I wish more answerers would look for that sign as an indication that the person needs to learn and doesn't need the answer coded for them.
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();
}
}
I have an assignment of which a part is to generate n random numbers between 0-99 inclusive in a 1d array, where the user enters n. Now, I have to print out those numbers formatted like this:
What is your number? 22 //user entered
1 2 3 4 5 6 7 8 9 10
----random numbers here---------
11 12 13 14 15 16 17 18 19 20
-----random numbers here--------
21 22
---two random numbers here---
Using those numbers, I have find lots of other things, (like min, max, median, outliers, etc.) and I was able to do so. However, I wasn't able to actually print it out in the format shown above, with no more than 10 numbers in one row.
Edit: Hello, I managed to figure it out, here's how I did it:
int counter = 0;
int count2 = 0;
int count3 = 0;
int add = 0;
int idx = 1;
int idx2 = 0;
if (nums > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums;
count2 = nums;
}
if (nums%10 == 0) add = 0;
else add = 1;
for (int i = 0; i < nums/10 + add; i++)
{
for (int j = 0; j < count3; j++)
{
System.out.print(idx + "\t");
idx++;
}
System.out.println();
for (int k = 0; k < count2; k++)
{
System.out.print(numbers[idx2] + "\t");
idx2++;
counter++;
}
System.out.println("\n");
if (nums-counter > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums-counter;
count2 = nums-counter;
}
}
Thank you to everyone who helped! Also, please let me know if you find a way to shorten what I have done above.
*above, nums was the number of numbers the user entered
I'd use a for-loop to make an array of arrays: and then formatting the lines using those values:
var arr_random_n = [1,2,3,4,5,6,7,8,9,0,1,2,3,6,4,6,7,4,7,3,1,5,7,9,5,3,2,54,6,8,5,2];
var organized_arr = [];
var idx = 0
for(var i = 0; i < arr.length; i+=10){
organized_arr[idx] = arr.slice(i, i+10); //getting values in groups of 10
idx+=1 //this variable represents the idx of the larger array
}
Now organized_arr has an array of arrays, where each array in index i contains the values to be printed in line i.
There's probably more concise ways of doing this. but this is very intuitive.
Let me know of any improvements.
Something like this might be what you're looking for.
private static void printLine(String msg)
{
System.out.println("\r\n== " + msg + " ==\r\n");
}
private static void printLine(int numDisplayed)
{
printLine(numDisplayed + " above");
}
public static void test(int total)
{
int[] arr = new int[total];
// Fill our array with random values
for (int i = 0; i < total; i++)
arr[i] = (int)(Math.random() * 100);
for (int i = 0; i < total; i++)
{
System.out.print(arr[i] + " ");
// Check if 10th value on the line, if so, display line break
// ** UNLESS it's also the last value - in that case, don't bother, special handling for that
if (i % 10 == 9 && i != total - 1)
printLine("Random Numbers");
}
// Display number of displayed elements above the last line
if (total < 10 || total % 10 != 0)
printLine(total % 10);
else
printLine(10);
}
To print 10 indexes on a line then those elements of an array, use two String variables to build the lines, then print them in two nested loops:
for (int i = 0; i < array.length; i += 10) {
String indexes = "", elements = "";
for (int j = 0; j < 10 && i * 10 + j < array.length; j++) {
int index = i * 10 + j;
indexes += (index + 1) + " "; // one-based as per example in question
elements += array[index] + " ";
}
System.out.println(indexes);
System.out.println(elements);
}
Number Pattern
I am asked to enter a number rc, and based on rc construct this pattern. I am able to initialize the table but without the highlighted numbers:
int [][] num2 = new int [rc][rc];
counter = 1;
for(int i = 0; i < rc; i++){
if(i!=0)
counter--;
for(int j =0; j < rc; j++){
num2 [i] [j] = counter;
counter ++;
}
}
Any hints or ideas?
You got it partially right. The numbers printed on each row are the same but the start point is incremented by 1 each time. Thus, you can use variable i again to shift it.
int [][] num2 = new int [rc][rc];
int counter = 1;
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
num2[i][(j + i) % rc] = counter++;
}
}
The following code is working fine for your problem.
int rc=5;
int [][] num2 = new int [rc][rc];
int counter = 1;
for(int i = 0; i < rc; i++){
for(int j =i; j < rc; j++){
num2 [i] [j] = counter;
counter ++;
}
for(int k =0; k < rc; k++){
if(num2[i][k]==0){
num2 [i] [k] = counter;
counter++;
}
System.out.print(num2[i][k]+"\t");
}
System.out.println();
}
The logic behind my solution is:
First fill an array from 1 - N, where N is the user input (or
rc in this case):
Then, we check if it's not the first line, if it is, we simply print
the numbers in order.
Now, we have to know which numbers go first:
In the line 1 (remember it starts from 0), it must print the number at [1][4] in [1][0], so our loop substracts rc - i + j, this gives: 5 - 1 + 0, which in fact is index [4].
We know that after we've printed the last numbers first, we must continue the sequence, so we print index: [1][0] at [1][1] (Why 1, 2? Because otherwise we would get something like the example below, that's why we need to substract 1 to it
1 2 3 4 5
10 7 8 9 10
And that's it:
public class StrangePattern {
public static void main(String[] args) {
int rc = 5;
int number = 1;
int spaces = 0;
int[][] numbers = new int[rc][rc];
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
numbers[i][j] = number;
number++;
}
}
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
if (i != 0) {
if (j < i) {
System.out.print(numbers[i][rc - i + j] + "\t");
} else {
System.out.print(numbers[i][j - spaces] + "\t");
}
} else {
System.out.print(numbers[i][j] + "\t");
}
}
spaces++;
System.out.println();
}
}
}
Which provides this output:
1 2 3 4 5
10 6 7 8 9
14 15 11 12 13
18 19 20 16 17
22 23 24 25 21
And this one for rc = 3:
1 2 3
6 4 5
8 9 7
I added the plus 1 here: for (int i = 1; i < x + 1; i++) {
for (int j = 1; j < y + 1; j++)
so that the program would grab all the numbers except the one right before what I mean is..
If I enter 10 for the Maximum x value and 10 for the y (without the plus 1) this is what the output shows:
Would you like a power table or a multiplication table?
Press 1 for Power
Press 2 for Multiplication
2
Maximum x value?
10
Maximum y value?
10
1 2 3 4 5 6 7 8 9
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
I don't know why this wont work please help this is the code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int defaulVa = 1;
int defaulEx = 2;
System.out.println("Would you like a power table or a multiplication table?"
+ "\n Press 1 for Power"
+ "\n Press 2 for Multiplicatiion");
int a = sc.nextInt();
System.out.println("Maximum x value?");
int x = sc.nextInt();
System.out.println("Maximum y value?");
int y = sc.nextInt();
switch (a) {
case 1:
System.out.println("How would you like your base?"
+ "\nPress 1 for preset value"
+ "\nPress 2 for acending value");
int answer = sc.nextInt();
switch (answer) {
case 1:
System.out.println("What value?");
int value = sc.nextInt();
powerTable(x, y, value, defaulVa);
break;
case 2:
System.out.println("How would you like your exponent?"
+ "\nPress 1 for preset value"
+ "\nPress 2 for acending value");
int d = sc.nextInt();
switch (d) {
case 1:
System.out.println("What value?");
int d2 = sc.nextInt();
powerTable(x, y, defaulVa, d2);
break;
case 2:
powerTable(x, y, defaulVa, defaulEx);
break;
default:
break;
}
break;
default:
break;
}
break;
case 2:
multiplicationTable(x, y);
break;
default:
System.out.println("I see you can't follow simple instructions...");
System.exit(0);
break;
}
}
public static int[][] powerTable(int arrayDimensionX, int arrayDimensionY, int value, int value2) {
int[][] myArray;
myArray = new int[arrayDimensionX][arrayDimensionY];
for (int i = 1; i < myArray.length; i++) {
for (int j = 1; j < myArray[i].length; j++) {
if (value == 1) {
value = myArray[i][j] = i * j;
} else if (value != 1) {
value++;
}
myArray[i][j] = ((int) Math.pow(value, value2));
}
}
for (int i = 1; i < arrayDimensionX; i++) {
for (int j = 1; j < arrayDimensionY; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
return myArray;
}
public static int[][] multiplicationTable(int x, int y) {
int[][] myArray;
myArray = new int[x][y];
for (int i = 1; i < myArray.length; i++) {
for (int j = 1; j < myArray.length; j++) {
myArray[i][j] = i * j;
}
}
for (int i = 1; i < x + 1; i++) {
for (int j = 1; j < y + 1; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
return null;
}
}
Arrays are 0 indexed (they start at 0 and the last index is length - 1)
I would say...
for (int i = 1; i < x + 1; i++) {
for (int j = 1; j < y + 1; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
Should be...
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
You'd need to change the loop that builds the table to look something more like...
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray.length; j++) {
myArray[i][j] = (1 + i) * (1 + j); // <-- Modify the indices here instead...
}
}
Have a look at Arrays for more details
Why does your multiplicationTable function have an int[][] return type, when you return null? Would be better to just make it a void function, if you don't plan on having it return the array.
Anyway, since all the function does in print to the screen, the function is over complicated. Could be made much simpler, something like this:
public static void multiplicationTable(int x, int y)
{
for (int i = 1; i <= x; i++)
{
for (int j = 1; j <= y; j++)
System.out.print(i * j);
System.out.println();
}
}
But if you want it left as is, your ArrayIndexOutOfBounds exception is likely occuring here:
for (int i = 1; i < x + 1; i++) {
for (int j = 1; j < y + 1; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
Because x and y are the size of the array, making your loop go to i < x + 1 and i < y + 1 will throw the exception, because it is trying to access a non-existing index. If you change it to i < x and i < y it shouldn't throw the exception:
for (int i = 1; i < x; i++) {
for (int j = 1; j < y; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
However, even that will not give you the desired output, as it skips the first element of the array, because array indexes start at 0, not 1, meaning the multiplications for 1 will be missing from your table.
I tried like this,
for (int j = 1; j <= 4; j++) {
for (int k = 1; k < 10; k++) {
if (k <= j) {
System.out.print(k + " ");
} else
break;
}
System.out.println();
}
but it prints like
1
1 2
1 2 3
1 2 3 4
This question is asked in one interview i had attended, my mind is breaking to find solution.. i can't think..
init a variable before
int printed = 1;
and change your
System.out.print(k+" ");
with
System.out.print(printed+" ");
printed++;
This will do it :
public static void main(String[] args)
{
int i, j, k;
for (i = 1, j = 1; i < 11; j++)
{
for (k = 0; k < j; k++)
{
System.out.print(i++ + " ");
}
System.out.println();
}
}
This code will do that:
int i, j, k;
for (i = 1, j = 1; i < 11; j++) {
for (k = 0; k < j; k++)
System.out.print(i++ + " ");
System.out.print("\n");
}
Basically, i controls the next number to print, and j controls how many numbers you will print in the current line. k is just a counter for j.
You can also try this with some mathematic magic (sequences).
for (int j = 1; j <= 4; j++) {
for (int k=(int) (0.5*(Math.pow(j,2)-j+2));k<=(int) (0.5*j*(j+1));k++) {
System.out.print(k + " ");
}
System.out.println();
}