Can somebody explain this nested loop? - java

I have the solution to the code, but I don't understand how it works. Can somebody explain?
for (int i = 1; i <= 3; i++)
for (int j = i; j <= 4; j++)
System.out.print(j + " ");
The output for the code is 1 2 3 4 2 3 4 3 4

j starts at i=1 and goes to 4.
i increments.
j starts at i=2 and goes to 4.
Rinse, repeat...
Maybe this visual helps delineate the loops
1 2 3 4 | 2 3 4 | 3 4

At the beginning I is at 1 so j goes to 1 to 4 right
Than I pass to 2 so j goes to 2 to 4 cuz I=j remember
Than I pass to 3 so j goes to 3 to 4 and voila
You get: 1234 234 34...

Related

Printing a squares triangle. How to mirror numbers?

So I've been working on this lab for a while now for my programming class and so far I think I'm on the right track.
However, I'm not quite sure how to mirror the numbers. So pretty much, my code is only printing the top half of the triangle. Anyway here is the actual assignment that was given to us:
Write a program using a Scanner that asks the user for a number n between 1 and 9 (inclusive). The program prints a triangle with n rows. The first row contains only the square of 1, and it is right-justified. The second row contains the square of 2 followed by the square of 1, and is right justified. Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2 and 1, and so forth until n rows are printed.
Assuming the user enters 4, the program prints the following triangle to the console:
1
4 1
9 4 1
16 9 4 1
9 4 1
4 1
1
For full credit, each column should be 3 characters wide and the values should be right justified.
Now here is what I have written for my code so far:
import java.util.Scanner;
public class lab6 {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println(
"Enter a number that is between 1 and 9 (inclusive): ");
// this is the value that the user will enter for # of rows
int rows = kybd.nextInt();
for (int i = rows; i > 0; i--) {
for (int j = rows; j > 0; j--)
System.out.print((rows - j + 1) < i ?
" " : String.format("%3d", j * j));
System.out.println();
}
}
}
And this is what that code PRINTS when I enter 4:
Enter a number that is between 1 and 9 (inclusive):
4
1
4 1
9 4 1
16 9 4 1
As you can see, I can only get the TOP half of the triangle to print out. I've been playing around trying to figure out how to mirror it but I can't seem to figure it out. I've looked on this website for help, and all over the Internet but I can't seem to do it.
Answer is:
public static void main(String... args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter a number that is between 1 and 9 (inclusive): ");
int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows
for (int i = -rows + 1; i < rows; i++) {
for (int j = -rows; j < 0; j++)
System.out.print(abs(i) > j + rows ? " " : String.format("%3d", j * j));
System.out.println();
}
}
Try think of this as how to find points(carthesians) that are betwean three linear functions(area of triangle that lied betwean):
y = 0 // in loops i is y and j is x
y = x + 4
y = -x -4
And here is example result for 4:
And 9:
In the outer loop or stream you have to iterate from 1-n to n-1 (inclusive) and take absolute values for negative numbers. The rest is the same.
If n=6, then the triangle looks like this:
1
4 1
9 4 1
16 9 4 1
25 16 9 4 1
36 25 16 9 4 1
25 16 9 4 1
16 9 4 1
9 4 1
4 1
1
Try it online!
int n = 6;
IntStream.rangeClosed(1 - n, n - 1)
.map(Math::abs)
.peek(i -> IntStream.iterate(n, j -> j > 0, j -> j - 1)
// prepare an element
.mapToObj(j -> i > n - j ? " " : String.format("%3d", j * j))
// print out an element
.forEach(System.out::print))
// start new line
.forEach(i -> System.out.println());
See also: Output an ASCII diamond shape using loops
Another alternative :
public static void main(String args[]) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter a number that is between 1 and 9 (inclusive): ");
int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows
int row = rows, increment = -1;
while (row <= rows){
for (int j = rows; j > 0; j--) {
System.out.print(rows - j + 1 < row ? " " : String.format("%3d", j * j));
}
System.out.println();
if(row == 1) {
increment = - increment;
}
row += increment;
}
}
The outer loop from 1-n to n-1 inclusive, and the inner decrementing loop from n to 0. The if condition is the absolute value of i should not be greater than n - j.
Try it online!
int n = 6;
for (int i = 1 - n; i <= n - 1; i++) {
for (int j = n; j > 0; j--)
if (Math.abs(i) > n - j)
System.out.print(" ");
else
System.out.printf("%3d", j * j);
System.out.println();
}
Output:
1
4 1
9 4 1
16 9 4 1
25 16 9 4 1
36 25 16 9 4 1
25 16 9 4 1
16 9 4 1
9 4 1
4 1
1
See also: Invert incrementing triangle pattern

Number Pattern Printing in Java

I'm newbie to programming. So as an exercise, I'm trying to print a number pattern like below
4
34
234
1234
I tried the below code
public static void main(String[] args) {
// TODO Auto-generated method stub
int n =4;
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j++) {
System.out.print(" ");
}
int num = 4;
for (int j = 1; j <= i; j++) {
System.out.print(num);
num--;
}
System.out.println("");
}
}
but it is printing in this way.
4
43
432
4321
I think, I have to decrement the value before printing. Please correct me if i'm wrong. But I'm stuck here. Can anyone please help me?
This is the pattern you want to get:
4
34
234
1234
When you describe the pattern in words, it could look like this:
line 1 has 3 spaces, and then the digit 4
line 2 has 2 spaces, and then the digits 3 and 4
line 3 has 1 space, and then the digits 2 to 4
line 4 has 0 spaces, and then the digits 1 to 4
There is already some kind of pattern here. The last two lines look remarkably similar. Let's see whether the first two lines can be brought into the same form:
line 1 has 3 space(s), and then the digits 4 to 4
line 2 has 2 space(s), and then the digits 3 to 4
line 3 has 1 space(s), and then the digits 2 to 4
line 4 has 0 space(s), and then the digits 1 to 4
Now that looks good. The next step is to change the wording to depend on the given line:
line i has (4 - i) space(s), and then the digits (4 - i + 1) to 4
I took care not to say 5 instead of the 4 + 1, so that the 4 is still visible. Let's give this 4 another name:
line i has (max - i) space(s), and then the digits (max - i + 1) to max
Now you should be able to translate this instruction into Java code.
You only need one inner for-loop.
I use the ternary operator (also called elvis-operator because ?:) to decide whether to print the number or a blank space:
int n = 7;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(j > n-i ? j : " ");
}
System.out.println();
}
It prints
7
67
567
4567
34567
234567
1234567
You actually only need one nested loop in this situation:
int n = 4;
for (int i = n; i > 0; i--) {
for (int j = 1; j <= n; j++) {
if (j < i) {
System.out.print(" ");
} else {
System.out.print(j);
}
}
System.out.println();
}
So loop from 0 to n and either print a space, or print the number if the inner counter is less than i.
Output:
4
34
234
1234

Using Nested for loops to make a doubling then halfing pyramid

1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
I need to make this pyramid using nested for loops,
so far all I have figured out is that I need three for loops.
I know how for loops work and have a pretty good grasp on the fundamentals of java, but I have no earthly idea on how this works.
Just wrote this without debug but it should produce this pyramid:
0
0 1 0
0 1 2 1 0
0 1 2 3 2 1 0
int pyramidHeight = 4;
for(int i = 0; i < pyramidHeight;i++){
for(int j = 1; j < pyramidHeight*2;j++){
if( j < pyramidHeight - i || j > pyramidHeight + i ){
System.out.print(" ");
}
else{
System.out.print(i - Math.abs(pyramidHeight - j));
}
System.out.print(" ");
}
System.out.println();
}
With two simple changes you should get your pyramid.
This should work! Note that you have each row counting total 2*i+1 elements where i is your current row number.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int lim = 5;
int spaceLim = lim*2;
for (int i=0; i < lim; i++){ // Number of rows is the key here (pow 2)
String s = "%" + spaceLim + "s";
System.out.printf(s, "");
if (i == 0){
System.out.print(1);
}
else{
for (int j=0; j<i; j++) {
System.out.printf("%1.0f ",(Math.pow(2.0, (double)(j))));
}
for (int j=i; j>=0; j--){
System.out.printf("%1.0f ", (Math.pow(2.0, (double)(j))));
}
}
System.out.println();
spaceLim -= 2;
}
}
}
The demo of working solution is here - http://ideone.com/J2fcQw

How to display a 2D table in java

I try do disply a 2 D table but for some reason I can't, I don't see what i wrote wrong.
This is my code (I am working in vim):
int [][] tab = new int [5][5];
for (int i= 0; i<tab.length ; i++){
for (int j =0; j<tab[i].length; j++){
tab[j][i]=i;
System.out.println("" + tab[j][i]);
}
System.out.println("");
}
}
The result of this code is:
0
0
0
0
1
1
1
1
2
2
2
2
3
3
3
3
4
4
4
4
And i want:
0
0
0
0
1
1
1
1
2
2
2
2
3
3
3
3
4
4
4
4
Can someone help me with this?
Thank you
In the inner loop, replace: -
System.out.println("" + tab[j][i]);
with: -
System.out.print(" " + tab[j][i]);
since you want to continue printing in the same row.
The problem is that System.out.println("" + tab[j][i]);
print a whole line in your output, if you change the
System.out.println("" + tab[j][i]);
with
System.out.print(tab[j][i] + " ");
adding a blank space, you will print the String in the line but it wont break and
start in a new line. Try what #Rohit Jain post, this is a correct solution...
You need to change the code
int [][] tab = new int [5][5];
for (int i= 0; i<tab.length ; i++){
for (int j =0; j<tab[i].length; j++){
tab[i][j]=i;
System.out.print( tab[i][j]+" ");
}
System.out.println("");
}
Cause your outer loop run for every row and the inner for every column. So you must use tab[i][j] (the convention is tab[row][col]) to make the code error free. And here in your case you have equal rows & columns. But problem may arise when they are different.

How can I go through a 2D Array via the secondary diagonal?

As I said, I would like to "scroll" through a Multi Dimensional array via the secondary diagonal, my desired input to be: (Case a) [It can be in either C++ or Java, it doesn't matter]
NOTE+EDIT: The order is not random. It starts from the 1 at the bottom and goes its way up.
Is this possible?
If not then at least half of the code? (Case b)
// Case a:
16 15 13 10
14 12 9 6
11 8 5 3
7 4 2 1
// Case b:
0 0 0 1
0 0 9 6
0 8 5 3
7 4 2 1
You can do this with a simple loop (this is Java):
int size = 4;
int[][] matrix = new int[size][size];
// . . .
for (int i = 0; i < size; ++i) {
doSomethingWith(matrix[i][size - i - 1]);
}
int[][] a={{7,6,4,1},{5,3,9,6},{2,8,5,3},{7,4,2,1}};
for(int i=0; i<a.length; i++)
{
for(int j=a[i].length-1; j>=a[i].length-(i+1); j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}

Categories

Resources