I am trying to write a collection of for-loops that produce the following series of numbers below. I am trying to accommodate my loops to print each series on the same line, with spaces between each term. I am new to java and got really confused on how exactly I can accomplish it. On the right side are the digits I am increasing the counting by.
1. 4 5 6 7 8 9 10 (+1)
2. 6 5 4 3 2 1 (-1)
3. 2 4 6 8 10 12 14 16 (+2)
4. 19 17 15 13 11 9 7 5 (-2)
5. 7 15 23 31 39 (+8)
6. 2 4 8 16 32 64 (*2)
Here is the code the way I tried to accomplish it. I got the first row to work but I'm wondering weather there's an easy way I can create the rest of them without re-duplicating the program.
import acm.program.*;
public class ppLoop extends ConsoleProgram {
public void run()
{
{
for(int row = 1; row < 2; row++)
{
print(" " + row + ". ");
for (int col = 4; col < 11; col++)
{
print(row*col + " ");
} //col values
println( );
} //row values
}
}
}
I am new to java and right now going over for-loops and trying to accomplish this in for-loop. If someone could help me out, I would really appreciate it.
Thank you!
Edit:
Here is what happens when I increase the number of rows.
Edit:
Here is the solution of what I had tried accomplishing. Thanks to everyone who helped me.
import acm.program.*;
public class ppLoop extends ConsoleProgram
{
public void run()
{
{
for(int i = 1; i < 2; i++) // One iteration of outer loop
{
print(i + ". "); // print row number 1
for (int j = 4; j < 11; j++) // loop for row 1
{
print(j + " ");
}
println( );
print((i + 1) + ". ");
for (int j = 6; j > 0; j--) // loop for row 2
{
print(j + " ");
}
println();
print((i + 2) + ". ");
for (int j = 2; j < 17; j = j + 2) // loop for row 3
{
print(j + " ");
}
println();
print((i + 3) + ". ");
for (int j = 19; j > 4; j = j - 2) // loop for row 4
{
print(j + " ");
}
println();
print((i + 4) + ". ");
for (int j = 7; j < 40; j = j + 8) // loop for row 5
{
print(j + " ");
}
println();
print((i + 5) + ". ");
for (int j = 2; j < 65; j = j * 2) // loop for row 6
{
print(j + " ");
}
println();
}
} //close outer loop
} //close public run
} //close console program
You can perform this program with a series of nested loops. I have done the first three rows. I took out your package and used a main method. Also, your indentation was very confusing. Since your increment changes each line, I don't know of a way to make it any shorter than this using for loops.
public class ppLoop{
public static void main(String[] args)
{
{
for(int i = 1; i < 2; i++) // One iteration of outer loop
{
System.out.print(i + ". "); // print row number
// you can use the same variable for each inner loop
for (int j = 4; j < 11; j++) // loop for row 1
{
System.out.print(j + " ");
}
System.out.println( );
System.out.print((i + 1) + ". ");
for (int j = 6; j > 0; j--) // loop for row 2
{
System.out.print(j + " ");
}
System.out.println();
System.out.print((i + 2) + ". ");
for (int j = 2; j < 17; j = j + 2) // loop for row 3
{
System.out.print(j + " ");
}
}
}
}
}
You could create a method that takes:
1. A start number
2. What math operation to perform (add, subtract, or multiply)
3. What number to increment/decrement or multiply by
4. An end number
It would look similar to this:
public void formattedFor(int startNum, String operation, int num, int endNum) {
if (operation.equals("add")) {
for (int i = startNum; i < endNum; i += num) {
System.out.print(i + " ");
}
}
if (operation.equals("sub")) {
for (int i = startNum; i > endNum; i -= num) {
System.out.print(i + " ");
}
}
else if (operation.equals("mult")) {
for (int i = startNum; i < endNum; i *= num) {
System.out.print(i + " ");
}
}
System.out.println( );
}
If I'm understanding the problem, you want to print six series that each start with a different number and increment/decrement that number by some value. Since I see no relationship between the initial value and the increment/decrement, you're going to have to write six separate for loops.
If you're absolutely averse to this, you can store your initial values, your increments/decrements, and your final values in an array and iterate through them using a for loop, an if statement (to deal with the multiplication) and a while loop. The array would look like this:
int[][] values = new int[][] {
{4, 6, 2, 19, 7, 2},
{1, -1, 2, -2, 8, 2},
{10, 1, 16, 5, 39, 64}
};
I could write up the source based on this, but it's not what you asked for.
I strongly suspect that, if this is a homework assignment and you've modified the problem, there's something you've failed to understand about the problem itself. If this is meant to have an simple solution that uses for loops, there should probably be some logic that binds the rows together, unless you're allowed to use arrays/while loops/for loops/objects and methods.
On another note, you should format your code differently. It's somewhat difficult to read right now. In general, indent things that happen inside loops, classes, or functions. For example:
import acm.program.*;
public class ppLoop extends ConsoleProgram {
public void run() {
for(int row = 1; row < 2; row++) {
print(" " + row + ". ");
for (int col = 4; col < 11; col++) {
print(row*col + " ");
} //col values
println( );
} //row values
}
}
Related
I am having problems with my code.
The goal with my code is for a user to enter a number which is then used to form
a multiplication-table. For example, if the user enters the number 4, the program is supposed to print following:**
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
This is my current code. Thankful for any kind of help!
import java.util.Scanner;
public class MultiplicationTable {
public static void main (String[] arg) {
Scanner gt = new Scanner(System.in);
System.out.println("Enter a number for multiplication: ");
int N = gt.nextInt();
for(int i = 1; i < N; i++) {
for(int j = 1; j < N; j++);
int product = i * j;
System.out.print(i +" * " +j +" = " +product );
System.out.println();
}
}
}
There are two tiny errors in your code, otherwise you are good to go.
for(int i = 1; i < N; i++) {
for(int j = 1; j < i; j++); //<-- remove this semicolon
{ // <-- use curly braces here for the loop statements
int product = i * j;
System.out.print(i +" * " +j +" = " +product+" "); //<--add an additional space at the end
}
System.out.println();
}
To get that pyramidal structure, you should change the second loop limit to i :
for(int j = 1; j < i; j++)
And remove the semicolon at the end of the loop.
I have a requirement to print the matrix in a snake form. So for this matrix, the output should be:
My question is that this code throws ArrayIndexOutofBounds. How can I handle that to avoid this?
int[][] mat= {{1,2,3},{4,5,6},{7,8,9}};
int row=mat.length;
int col=mat[0].length-1;
int c=col;
int r=0;
while(r < row) {
for(int j=c;j>=0;j--) {
// System.out.print("r: " + r);
// System.out.print(" " + mat[r][j]);
}
r=r+1;
for(int j=0;j<=c;j++) {
// System.out.print("r: " + r);
//System.out.print(" " + mat[r][j]);
}
r=r+1;
}
3 2 1 4 5 6 9 8 7
This is how I would have gone about it:
int[][] mat= {{1,2,3},{4,5,6},{7,8,9}};
int row=0;
while(row < mat.length) {
if(row%2 == 0){ //if an even row, go right to left
int col = mat[0].length - 1;
while(col >= 0) { System.out.print(mat[row][col]); col--; }
}else {
int col = 0;
while(col < mat[0].length) { System.out.print(mat[row][col]); col++; }
}
row++;
}
where you are going wrong is in incrementing r inside the loop and not checking if it's still less then the length before printing.
you can also add this check to your code for it to start working:
.
.
r=r+1;
if(r >= row)
break;
for(int j=0;j<=c;j++) {
.
.
.
I see that the second line says:
int row=mat.length;
Because array indexes start at 0, you should change it to:
int row=mat.length-1;
to avoid getting an exception when calling mat[row].
Here is one way. It is important to take the row length to allow for ragged arrays.
int[][] mat = { { 1, 2, 3
}, { 4, 5, 6
}, { 7, 8, 9, 10, 11
}, { 12, 13
}, { 14, 15, 16, 17, 18, 19
}
};
for (int r = 0; r < mat.length; r++) {
if (r % 2 == 0) {
for (int c = mat[r].length - 1; c >= 0; c--) {
System.out.print(" " + mat[r][c]);
}
}
else {
for (int c = 0; c < mat[r].length; c++) {
System.out.print(" " + mat[r][c]);
}
}
}
Note that if you want to snake left to right, then modify it to use r % 2 == 1. If you want to go bottom up, change your outer loop to start at the last row.
Your code throws ArrayIndexOutOfBounds exception because r becomes 3 (r=r+1) on second iteration and you try to access mat[3][2] (ie. you are accessing the values of fourth row which is not available)
for(int row = 0; row < mat.length; row++){
if(row%2 == 0) {
// print the elements in reverse order
}
else {
//print the elements as in given matrix
}
}
Thus all your odd rows' (ie. 1st, 3rd, 5th row..) elements will be printed in reverse order and even rows' elements will be printed as in given matrix
Instead of initializing so many variables you can just set up the for loops which first determine if we are starting at the end or beginning of the row and then iterate over all the integers.
int[][] mat= {{1,2,3},{4,5,6},{7,8,9}};
for(int row = 0; row < mat.length; row++){
if(row%2 == 0){
for(int col = mat[row].length -1; col >= 0; col--){
System.out.print(mat[row][col] + " ");
}
}else{
for(int col = 0; col < mat[row].length; col++){
System.out.print(mat[row][col] + " ");
}
}
}
I want to create a matrix of size N by N where N is a constant value defined globally, for now I just want to create a matrix where N=6. Where I fall short is I want to make it diagonally, like so:
0 1 2 3 4 5
1 0 1 2 3 4
2 1 0 1 2 3
3 2 1 0 1 2
4 3 2 1 0 1
5 4 3 2 1 0
Currently I have this method:
public static void drawMatrix(){
for (int line = 0; line < N; line++){
for (int j = 0; j < N; j++){
System.out.print(j + " ");
}
System.out.println();
}
}
Unfortunately it's only able to print 0 1 2 3 4 5 in every line, so I suppose I need another nested for-loop, however I'm not sure how to set it up.
j is the column number, so it will be the same for all rows. What you need to do is to add or subtract j from the line number, depending on the line number, in order to make a "shift". Since the result could become negative, you will need to add N and mod by N:
if (j > line) {
System.out.print((N-line+j)%N + " ");
} else {
System.out.print((line-j+N)%N + " ");
}
Demo.
You can also rewrite it without an if using a conditional expression:
int sign = j > line ? -1 : 1;
System.out.print((N+sign*(line-j))%N + " ");
Demo.
A little change in your code works
public static void drawMatrix() {
for(int line = 0; line < N; line++) {
for(int j = 0; j < N; j++) {
System.out.print(Math.abs(line - j) + " ");
}
System.out.println();
}
}
I would do something like :
int n=6;
for(int row=0;row<n;row++)
{
for(int col = 0;col<n;col++)
{
System.out.print(abs(col-row) +" ");
}
System.out.println();
}
assuming you can use abs().
I hoped that help your purpose.
This also works :
public static void main(String[] args) {
int N = 6;
int column = 0;
for (int row = 0; row < N; row++) {
for (column = row; column >= 0; column--) //prints till row number reaches 0
System.out.print(column + " ");
for (column = 1; column < N - row; column++)//from 1 to N-row
System.out.print(column + " ");
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");
}
#1
#2 3
#4 5 6
#7 8 9 10
#11 12 13 14 15
this is the required pattern and the code which i used is
public class Test{
public static void main(String[] args) {
int k = 1;
for (int i = 0; i <= 5; i++){
for (int j = 1; j <= i; j++){
System.out.print(k + " ");
k++;
}
System.out.println();
}
}
}
as you can see i used the variable k to print the numbers.
My question is that is there a way to print the exact same pattern without using the third variable k?
I want to print the pattern using only i and j.
Since this problem is formulated as a learning exercise, I would not provide a complete solution, but rather a couple of hints:
Could you print the sequence if you knew the last number from the prior line? - the answer is trivial: you would need to print priorLine + j
Given i, how would you find the value of the last number printed on i-1 lines? - to find the answer, look up the formula for computing the sum of arithmetic sequence. In your case d=1 and a1=1.
You can use this:
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < i; j++) {
System.out.print((i * (i - 1)) / 2 + j + 1 + " ");
}
}
}
Or you can the find the nth term and subtract it each time:
public static void main(String[] args) {
for (int i = 0; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(((i * (i + 1)) / 2) - (i - j) + " ");
// k++;
}
System.out.println(" ");
}
}
You can use
System.out.println((i+j) + " ");
e.g.
i j (i+j)
0 1 1
1 1 2
2 1 3
2 2 4
..........