Understanding how nested for loop works - java

I can't understand how nested for loop works. Just doing ascending order program please explain me step by step how it works
class Ascending {
public static void main(String args[]) {
int temp;
int a[] = {20, 10, 80, 70};
for (int i = 0; i < 4; i++) {
System.out.println(a[i]);
}
for (int i = 0; i < 4; i++) {
for (int j = i + 1; j < 4; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("\n after:");
for (int i = 0; i < 4; i++) {
System.out.println(a[i]);
}
}
}
Output:
20
10
80
70
after:
10
20
70
80

How nester loops are working.
Well this is quite simple, a for loop is define as follow :
for(init;condition;increment)
init : is executed once at the beginning
condition : check before every execute (like a while)
increment : will be done after the code in the loop
Here, with one loop,
for (int i = 0; i < 4; i++) {
// code
}
This will be the same as
int i = 0;
while(i < 4){
// code
i++;
}
If you have nested loops, the idea is the same, the inner loop will need to execute as many time as the condition is true before the outer one can increment and check his condition again.
for (int i = 0; i < 4; i++) { //loop A
for (int j = i + 1; j < 4; j++) { //loop B
// code
}
}
loop A will start with i = 0, then loop B will start with j = i = 0.
The code will be execute until j => 4 to exit loop B. There, loop A will execute the increment part, i = 1.
The condition is still true so the loop will execute his code, the loop B will start with j = i = 1.
And again ... until loop A's condition is false.

Related

printing numbers with nested loops

I have to print the following numbers using nested loops, and I kinda have an idea how, but not how to execute it.
000111222333444555666777888999
000111222333444555666777888999
000111222333444555666777888999
My code so far is something like:
public class opgave_2 {
public static void main(String[] args) {
final int first = 3;
final int second = 3;
final int third = 9;
for (int i = 0; i <= first ; i++) {
for (int j = i; j <= second; j++) {
for (int k = j; k <= third; k++) {
System.out.print(i);
}
}
}
}
}
You should proceed by steps to resolve such problem.
First, you want to print a number 3 times :
int myNumber = 0;
for(int i=0; i<3; i++) {
System.out.print(myNumber);
}
Second, you want to repeat it 9 times and your number to vary from 0 to 9 (seems like an index of loop) :
for(int myNumber=0; myNumber<=9; myNumber++) {
for(int i=0; i<3; i++) {
System.out.print(myNumber);
}
}
Third, you want to display this line 3 times :
for(intj=0; j<3; j++) {
for(int myNumber=0; myNumber<=9; myNumber++) {
for(int i=0; i<3; i++) {
System.out.print(myNumber);
}
}
System.out.println(""); //new line
}
What about something like this:
for (int i = 0; i < 3; i++) {
for (int j = 0; j <= 9; j++) {
System.out.printf("%1$s%1$s%1$s", j);
}
System.out.println();
}
Which uses 2 nested loops. The first to print the line 3 times, and the second to print the numbers per line
you can use a loop, that loops 3 times. in that you put a loop that prints every number from 0 to 9 3 times in a row within the same line
for(int a = 0; a < 3; a++){
for(int i = 0; i < 10; i++){
System.out.print(i+""+i+""+i);
}
System.out.println(); //for the new line
}
or
for(int a = 0; a < 3; a++){
for(int i = 0; i < 10; i++){
System.out.print(i);
System.out.print(i);
System.out.print(i);
}
System.out.println(); //for the new line
}
this should do

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.

Is it possible to add conditional for loop in nested ones?

In an ordinary nested for-loop, is it possible to put a condition to determine whether to run a specific for loop in a nested loop?
For example, in a code like below, is it possible to skip second for-statement(int j) when int i of the first loop is < 3?
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 3; j++) {
for(int k = 0; k < 9; k++) {
//hell a lot of codes
}
}
}
so that only when i < 3, the actual executed code looks like this?
for(int i = 0; i < 5; i++) {
for(int k = 0; k < 9; k++) {
//hell a lot of codes
}
}
The reason why I want to do this is that the inner-most codes are quite long as well as the number of the for loops (about 10 nested), and really don't want to repeat them again. I can think of doing this with methods, but I am not quite familiar with methods and OO programming.
Much appreciated,
Generally, I'd probably extract the code to a separate method. But here's a workaround if you don't want to do that:
for(int i = 0; i < 5; i++) {
for(int j = 0; j < (i < 3 ? 1 : 3); j++) {
for(int k = 0; k < 9; k++) {
//hell a lot of codes
}
}
}
This way, if i < 3, the j loop will only execute once.
The method approach would roughly look something like this:
void outer() {
for(int i = 0; i < 5; i++) {
if(i < 3) {
inner(i, 0);
} else {
for(int j = 0; j < 3; j++) {
inner(i, j);
}
}
}
}
void inner(int i, int j) {
for(int k = 0; k < 9; k++) {
//hell a lot of codes
}
}
You may want to make the methods static, or private, or remove the parameter(s), or add a return type, etc. It's hard to say with just the code in your question.

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);
}
}
}

Arrays in for loops

I have an array called blockHeights, which contains 3 values inside of it, namely 1,2,3. So blockHeights[0] is equal to 1.
I also have a loop:
for (int i = 1; i <= blockHeights.length; i++)
In the first time around the loop, I want to create a variable called totalBlockHeights where it is
int totalBlockHeights = blockHeights[0] + blockHeights [1] + blockHeights [2];
However, in the next loop I want that variable to change, so that it only adds blockHeights[1] and blockHeights[2] together, ignoring blockHeights[0].
How would I go about doing this?
Try the following (I'm assuming the third iteration should only include blockHeights[2], following the pattern):
for (int i = 1; i <= blockHeights.length; i++) {
int totalBlockHeights;
for (int j = i - 1; j < blockHeights.length; j++) { // all block heights from here onwards
totalBlockHeights += blockHeights[j];
}
// do whatever
}
Well, if you want the sum of your array, and the sum of the array without first value
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++){
totalBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println("totalBlockHeights without first value = " + (totalBlockHeights - blockHeights[0]));
this way you only loop once
Try following code:
public class Loop {
public static void main(String[] argv) {
int[] blockHeights = new int[] {1, 2, 3};
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++) {
totalBlockHeights = 0;
for(int j = i; j < blockHeights.length; j++) {
totalBlockHeights += blockHeights[j];
}
System.out.println(totalBlockHeights);
}
}
}
int[] blockHeights = new int[] { 1, 2, 3 };
int totalBlockHeights = 0;
int customBlockHeights = 0;
for (int i = 0; i < blockHeights.length; i++) {
totalBlockHeights += blockHeights[i];
if (i == 0) {
continue;
}
customBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println(customBlockHeights);
This will print:
6
5
You dont need two for to achieve that.
you can perform this on two for loop outer loop for (int i = 1; i <= blockHeights.length; i++), and in inner loop (take a variable j) you can do like int totalBlockHeights = totalBlockHeights + blockHeights[j], and for i<j, you can just continue the for loop.
as answered by btrs20

Categories