Having trouble understanding this example on Multidimensional Array [duplicate] - java

This question already has answers here:
for loop without braces in java
(6 answers)
Closed 10 months ago.
For the code:
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][] = new int[4][5];
int i, j, k = 0;
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twoD[i][j] = k;
k++;
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
The output gives me:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
The question is, why isn't a new line given to every number? I mean in the for loop, if the first System.out outputted 20 times, why isn't the next System.out.println(); outputting the same amount?

If you used proper indentation, it would have been clearer :
for (i=0; i<4; i++) {
for (j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
System.out.println(); belongs to the outer loop, so it executes once for every iteration of the outer loop, after the inner loop ends.
You can also wrap the inner loop in curly braces to make it clearer :
for (i=0; i<4; i++) {
for (j=0; j<5; j++) {
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}

Without braces, a for loop body is one statement. If we add explicit braces, then your code looks like
for(i=0; i<4; i++) {
for(j=0; j<5; j++) {
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
which is why the println only executes after the inner for loop.

Related

How to understand Loops and Array in java

I am quite confused in array loops that do have nested ones to print the Two Dimensional array. /it contains a loop without curly braces and second one has just opposite way of representing the braces for loops ...
Since i am learning I have just typed the code and got output.
public class TwoDimensional {
private int i, j, k = 0;
int[][] twod = new int[4][5];
public void DoubleT() {
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++)
System.out.print(twod[i][j] + " ");
System.out.println();
}
}
}
The result it generates is
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
Try this :
public class TwoDimensional {
private int i, j, k = 0;
int[][] twod = new int[4][5];
public void DoubleT() {
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++){
System.out.print(twod[i][j] + " ");
}
System.out.println();
}
}
To properly use the braces always think about the purpose of the loops you have, when do you want them to finish and when do you want them to continue.
In your case, you'll need nested loops for different tasks so you have to properly delimit each one of those tasks.
Fill the the 2D array:
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
}
Print the 2D array values:
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++){
System.out.print(twod[i][j] + " ");
}
System.out.println();
}
Notice that, either for filling or printing the array, your first loop (iterator i) is responsible for the line. It'll stop at I = 3, line number 3. So you'll be in line 0 until you finish the values of all the columns on that line ( [0][0],[0][1],[0][2],[0][4] ) and you just want to go to the second line when your first line is totally filled or printed, and so on. On the print case, you'll need to change the line before the 'i' increments (new line number) and after you have all `'j' values.
To summarize, you'll just want to increment the line ('i') or go to the next line (println()), when your columns ('j') are finished.

Need Some Help w/ Nested For Loops in Java

I know this is extremely simple, but I need help with printing a code that displays
1
2 3
4 5 6
7 8 9 10
For some reason, my brain can't figure out how to do it, even though I am familiar with for loops, this is what I have so far.
for(int i = 1; i <= 4; ++i)
{
for(int j = 1; j <= i; ++j)
{
System.out.print(j);
}
System.out.println(" ");
}
I don't know what to do from here, it's been bugging me all day. Thank you!
int counter = 1;
for (int i = 1; i <= 4; ++i) {
for (int j = 1; j <= i; ++j) {
System.out.print(counter++);
System.out.print(" ");
}
System.out.println();
}
Use a counter variable to reach 10. Also move the space in the inner loop and add a line break in the outer loop.
Output:
1
2 3
4 5 6
7 8 9 10
Try this:
int i=0,j=0,n=4,k=1;
for(i=1; i<n+1; i++)
{
for(j=0; j<i; j++)
System.out.print(" "+k++);
System.out.println(" ");
}

Making a single number per line pyramid using nested loop and trying to center it

I have to create a number pyramid using nested loops for homework. I am very new to nested loops and am still not quite clear on how they work completely. My objective is to make this pyramid using nested loops:
-----1-----
----333----
---55555---
--7777777--
-999999999-
however I have only been able to get this:
----------1
--------333--
------55555----
----7777777------
--999999999--------
I think I am on the right track but I am not sure where to go from here.
Here is the code I currently have:
public class NumberPyramid
{
public static void main(String [] args)
{
for(int i=1; i<=9; i+=2)
{
for (int j = 11; j > i; j--)
{
System.out.print("-");
}
for(int j=1; j<=i; j++)
{
System.out.print(i);
}
for (int j = 1; j < i; j++)
{
System.out.print("-");
}
System.out.println();
}
}
}
The part of printing the numbers in the center is correct.
Printing the - before and after the numbers is incorrect.
Notice that for any row, the number of - before and after the numbers should be the same. How many - to print for a number?
For 1, print 5 - before and after.
For 3, print 4 - before and after.
For 5, print 3 - before and after.
That's (11 - i) / 2. Put this loop before and after the center line and you're done.
for (int j = 0; j < (11 - i) / 2; j++) {
System.out.print("-");
}
You should remove two - on every second line
int index = 5;
for (int i=1; i<=9; i+=2) {
for (int j=0; j<index; j++) {
System.out.print("-");
}
for (int k=0; k<i; k++) {
System.out.print(i);
}
for (int j=0; j<index; j++) {
System.out.print("-");
}
System.out.println();
index--;
}

Nested for loops 0123

I need to create a nested for loops that gives the following output,
0
1
2
3
This is what I have, but for the second test, userNum is replaced by 6 and obviously my code fails.. help?
public class NestedLoop {
public static void main (String [] args) {
int userNum = 0;
int i = 0;
int j = 0;
for(i = 0; i <= userNum; i++){
System.out.println(i);
for(i = 1; i <= userNum; i++){
System.out.println(" " +i);
for(i = 2; i <= userNum; i++){
System.out.println(" " +i);
for(i = 3; i <= userNum; i++){
System.out.println(" " + i);
}
}
}
}
return;
}
}
I think (it's a guess, though) that you're looking for this.
public static void main (String [] args)
{
int limit = 6;
for(int i = 0; i <= limit; i++)
{
for(int j = 0; j < i; j++)
System.out.print(" ");
System.out.println(i);
}
}
The reason why your approach fails is, as I see it, that you are looping through the numbers to show (which is right) but you fail to loop up on the number of spaces (which I resolved by relating the inner loop's limit to the outer loop's current value.
Let's talk a bit about what your intention is with these loops.
The inner loop is meant to produce an arbitrary number of spaces, depending on what number you're iterating on. So if you're on number 0, you produce no spaces, and if you're on 1, you produce one space, and so forth. The other caveat is that they all must appear on the same line, so System.out.println is the incorrect choice.
You would want to use System.out.print to print out the spaces. So let's write that.
for(int j = 0; j < 6; j++) {
System.out.print(" ");
}
This will print out six spaces unconditionally. What that condition is depends on the current number we're iterating on. That comes from your outer loop.
You only need to define a loop that starts from an arbitrary starting point - like 0 - and then loop until you are at most your ending number. For this, your current loop is sufficient:
for(i = 0; i <= userNum; i++) {
}
Now, we need to bring the two pieces together. I leave the figuring out of the question mark and what to print after you've printed the spaces as an exercise to the user, bearing in mind that you must stop printing spaces after you've reached your number.
for(int i = 0; i <= userNum; i++) {
for(int j = 0; j < ?; j++) {
System.out.print(" ");
}
}
Let's analyse the task
In every line, we should print a number and different number spaces in the front of the number.
For that, we need two loops - one outer to iterate from 0 to N and one inner to add spaces in front of the number.
private static void method1(int userNum) {
int nummSpaces = 0;
for (int i = 0; i <= userNum; i++) {
for (int j = 0; j < nummSpaces; j++) {
System.out.print(" ");
}
nummSpaces++;
System.out.println(i);
}
}
In this solution, we have variable numSpaces which used to count the number of spaces in front of the number. It is unneeded - we can use variable i for that purpose.
private static void method2(int userNum) {
for (int i = 0; i <= userNum; i++) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
System.out.println(i);
}
}
Let's analyses once again the output
- the fist line: printed zero spaces and number 0
- the second line: printed one space and number 1
- the third line: printed two spaces and number 2
- and so on
Finally, we can use just one variable, which contains spaces and after that print the length of it:
private static void method3(int userNum) {
for (String spaces = ""; spaces.length() <= userNum; spaces += " ") {
System.out.println(spaces + spaces.length());
}
}
C/C++
#include <iostream>
using namespace std;
int main() {
int userNum;
int i;
int j;
cin >> userNum;
for (i = 0; i <= userNum; ++i) {
for (j = 0; j < i; ++j) {
cout << " ";
}
cout << i << endl;
}
return 0;
}

nested loops and increment user input

I'm trying to print user input numbers and indent them by that number of spaces. I can't seem to get the numbers to indent, however, I am able to print them all vertically. Any help? Here is my code.
for (i = 0; i <= userNum; i++) {
for (j = 0; j < i; j++) {
System.out.println(i);
break;
If a user entered the number 3, my output would currently look like this:
1
2
3
When it should look like this:
1
2
3
This should do it
for (int i = 0; i <= userNum; i++) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
System.out.println(i);
}
You can try to add another for loop within that for loop. The print statement would be after this nested for loop. The inner loop would start from zero to i+1. In this for loop, you can print the spaces or tabs. Then after the for loop you can print the number. Make sure you do not include a new line inside the print statement in the inner for loop.
You haven't added the code yet to add the indenting. Try this:
public static void printNum(int userNum) {
for (int i = 0; i < userNum; i++) {
System.out.print(" ");
}
System.out.print(userNum+ "\n");
}
Calling it with:
printNum(10);
printNum(1);
printNum(2);
printNum(3);
Gives the following:
run:
10
1
2
3
BUILD SUCCESSFUL (total time: 0 seconds)
I hope this solves your problem :
for (i = 1; i <= userNum; i++)
System.out.format("%+(i-1)+s]%n", i);
public class Program {
public static void main(String[] args) {
int i = 3; // or your userNum
// this loop will iterates through 1 to i (or 1 to userNum for you)
for (int j = 1; j <= i; j++) {
// this loop iterates until j2 equals j (e.g. if j = 5, this loop will iterates 4 times)
for (int j2 = 1; j2 < j; j2++) {
// prints the space(s)
System.out.print(" ");
}
// prints the current number (in the first loop) and line break
System.out.println(j);
}
}
}

Categories