Nested for-loop output - java

I'm learning about Java loops and struggling to understand how an output was produced for a question regarding nested-for loops.
The code is:
for(int count = 0; count <=3; count++)
for(int count2 = 0; count2 < count; count2++)
System.out.println(count2);
The output produced was:
0
0
1
0
1
2
Can anyone please explain this as there isn't an explanation in the book like there usually is, thanks.

First loop variable: Count is looping to 3.
second loop variable: count2 is looping to count.
then you are printing the count 2. so first time you print nothing because 0 is not less then 0, and therefore stop right away because in that iteration count2 is not less then count. then count becomes 1, and at the time you are printing. Therefore you print 0. You follow this logic until count is <= 3, and count2 < count.
Here is a table that iterates through the loop: Hope this helped.

It is simple,Read this as
for(int count = 0; count <=3; count++) {
for(int count2 = 0; count2 < count; count2++) {
System.out.println(count2);
}
}
So when outer loop is 0,
inner loop will run 0 times as count2
So when outer loop is 1,
inner loop will run 1 times as count2<1 and hence it will run one time then count2 is incremented and so will fail and hence 0 as output
and similarly output continues till count is 3

Looking at
for (int count = 0; count <= 3; count++)
{
for (int count2 = 0; count2 < count; count2++)
{
System.out.println (count2);
}
}
You first enter the loop with count = 0;. Then the inner loop will not execute, since the initial condition is wrong (count2 < count is false since 0 < 0 = false). Then countincreases by one. The inner loop will then print all values which are strictly smaller than the outer loop variable (count). So if count = 1 the inner loop will print all numbers starting from 0 which are strictly smaller than 0, i.e. only 0 in that case. For count = 2, it will print 0,1 since these numbers are all strictly smaller than count. Same for count = 3, it prints the numbers 0,1,2. And that produces the output.
<No output from count = 0>
0 <from count = 1>
0
1 <from count = 2>
0
1
2 <from count = 3>

To understand this code change your code to following -
for (int count = 0; count <= 3; count++) {
for (int count2 = 0; count2 < count; count2++) {
System.out.print(count2 + " ");
}
System.out.println();
}
This will produce output as -
0
0 1
0 1 2

First of all your code would be clearer with curly braces and indentation :
for (int count = 0; count <=3; count++) {
for (int count2 = 0; count2 < count; count2++) {
System.out.println (count2);
}
}
Now the outer for loop will iterate 4 times with count getting values 0,1,2,3
the inner loop won't iterate for count == 0 so nothing is printed. For the values of count, count2 will be :
which explains the result you are getting

Related

Java - For loop seems to execute past it's termination condition

I have debugged this code and it appears to run a for loop even though the termination condition is met.
This program takes two types of input:
Line 1 - How many data points there are following (N)
Lines 2 to N - The data points
The program should then print the smallest difference between all of the data points.
So, for instance, a sample input would be (on separate lines): 3 5 8 9
There are 3 data points (5 8 9), and the smallest difference is between 8 and 9, so the program should return 1.
I am trying to build the program in a way in which the data points are populated into an array at the same time as the comparisons are made. Obviously I could separate those concerns, but I am experimenting. Here it is:
package com.m3c.vks.test;
import java.util.*;
import java.io.*;
import java.math.*;
class Solution {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int N = in.nextInt(); //How many data points there will be
int strengthArray[] = new int[N]; //Initialise the array to be of length = N, the first input line
int tempStrengthDifference=99999; //junk difference set arbitrarily high - bad practice I know
int lowestStrengthDifference=99999;
for (int i = 0; i < N; i++) //Go through all elements of array
{
strengthArray[i] = in.nextInt(); //read a value for the ith element
System.out.println("i: " + i); //test
if (i > 0) //do not execute the next for loop if i = 0 as cannot evaluate sA[-1]
{
for (int j = i - 1; j < 1; j--) // **this is line 20** from wherever the array has populated up to, work backwards to compare the numbers which have been fed in thus far
{
System.out.println("j: " + j); //test
tempStrengthDifference = Math.abs(strengthArray[i] - strengthArray[j]); //finding the difference between two values
if (tempStrengthDifference < lowestStrengthDifference) //store the lowest found thus far in lowestSD
{
lowestStrengthDifference = tempStrengthDifference;
}
}
}
}
System.out.println(lowestStrengthDifference);
}
}
Everything is fine up until when i = 1 on line 20. At this point, j is set to i - 1 = 0 and the difference is found. However, when the for loop comes back around again, the termination condition of j < 1 is not met, and instead the loop continues to set j = -1, at which point it throws an out of bounds error as it clearly cannot evaluate strengthArray[-1]
Any ideas? Thanks
Have a look at your loop: for (int j = i - 1; j < 1; j--)
You start with j = 0 when i == 1 and thus j < 1 is ok.
The next iteration has j = -1 (0-1) and hence you get the problem.
Do you mean to use j >= 0 as your loop condition instead? Note that the second parameter is not a termination condition but a continuation condition, i.e. as long as that condition is met the loop will execute.
The reason behind your failure is the inner loop variable change.
When i=1, j=0 and after executing the loop once, J is decremented, and thus j becomes - 1. The condition j<1 is satisfied since you have written j--, change it to j++ and you should be fine.

Java for loop with equality operator in the second condition

I am trying to print an array in reverse order.
Here is the code:
import java.util.Scanner;
public class Main {
public static void main(String []argh) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
for (int j = n-1 ; j == 0; j--) {
System.out.print(arr[j] + " ");
}
in.close();
}
}
In this code nothing happened, but when I changed the second condition in the 2nd for loop from j == 0 to j >=0 it worked. I don't understand why . In j==0, isn't that supposed to decrement j until it becomes equal to 0?
for (int j = n-1 ; j == 0; j--) means that the loop will execute as long as j is equal to 0. Since j is initialized to n-1, the loop is never executed (assuming n != 1).
The second argument to a for loop is the loop condition: it specifies the condition under which the loop body will execute. The body will execute while the condition is true, not until it is true.
Note how your first for loop works: i starts at 0, and it loops while i < n. It's the same principle in your second loop, only your loop variable moves in the opposite direction: j starts at n - 1, and should loop while j >= 0.
All conditional loops in Java (while, for, and do-while) work in this way: they loop only as long as the condition holds, then they terminate, and execution picks up after the loop.
In j==0 the condition will be false, because j is given a value which is equal to n-1, j=n-1.
Suppose the value of n is 3, so j will be equal to 2 then it'll come to condition checking part in for loop, in that part you've written like this j==0, since j isn't equal to 2 so the condition will be false and it'll come out of the for loop.

Why does this loop display this output?

for (int i = 1; i < 5; i++) {
int j = 0;
while (j < i) {
System.out.println("i = " + i + "\tj = " + j);
j++;
}
}
The output is:
i = 1 j = 0
i = 2 j = 0
i = 2 j = 1
i = 3 j = 0
i = 3 j = 1
i = 3 j = 2
i = 4 j = 0
i = 4 j = 1
i = 4 j = 2
i = 4 j = 3
My question is, why is the value of j=0 in the second line, even though we increment it after the first line was displayed?
Also, why is the value of i=2 twice, and i=3 thrice?
you declared int j=0; within the first loop so whenever the outer loop runs value of j set to be 0.
And reason of repeated value of i is the inner loop.For every time the loop runs the value of i is same for it.
Because you said that "until j is < than i" you increment j but the increment stops when j is = i so you have that i repeats for each increment of j.
I'm a bit confused about what your program should do but if I understood you should resolve your code like this:
for (i = 0; i < 5; i++) {
int j;
for (j = 0; j < i; j++) {
System.out.println("i = "+i+"\tj = "+j);
}
}
Outer for loop re-initialzes j to 0 in second iteration of the outer loop as it does in every iteration of the outer loop. Hence second line shows j as 0.
Since in second and third iteration of outer for loop, inner loop gets executed twice and thrice respectively, but outer loop variable value remains the same during the iteration of the outer loop. Hence, i=2 and i=3 is shown twice and thrice.
The j-variable and the i-variable in your code are going like this:
i=2:j=0->1: prints 2 times
i=3:j=0->1->2 prints 3 times
...
This concept is called nested loops. The for-loop is the outer loop, which has value of i from 1 to 4. In the inner while-loop, the value of j is initialized to 0 and it goes till j = i-1 (since the condition mentioned in while-loop is j < i).
You enter the first iteration of for-loop (i = 1). Now you enter the first iteration of while-loop (j = 0). Condition is true (0 < 1). i = 1 j = 0 is printed. In next iteration of while loop, j = 1, condition is false (1 not < 1). Hence while-loop is now exited.
Now in the second iteration of for-loop, i value is incremented (i = 2). Now you enter the first iteration of while-loop (j = 0). Condition is true (0 < 2). i = 2 j = 0 is printed. In next iteration of while loop, j = 1, condition is true (1 < 2). i = 2 j = 1 is printed. In next iteration of while loop, j = 2 , condition is false (2 not< 2). Hence while loop is exited.
As you can see, in the first iteration of for-loop print is executed only once. And in the second iteration of for-loop print is executed twice. This is because execution of print is dependent on the value of j being lesser than i (i increases by 1 every time). This pattern will repeat and for i = 3 print statement will be executed thrice and so on.
Hope you understood. If not, feel free to clear your doubts in the comments.

What is this Nested For Loop doing? (Asterisk Right Triangle)

I just started learning about "nested for loops". But my question what is the nested for loop exactly doing every time it loops? I'm still confused as to what is variable "i" is doing and what is variable "j" is doing. If you can explain what is happening after every loop, it would make nested for loops much clearer.
import java.util.Scanner;
public class LoopStatement {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numStar;
System.out.print("Number of stars: ");
numStar = input.nextInt();
while (numStar < 1 && numStar > 20) {
System.out.println("Enter a valid number ");
numStar = input.nextInt();
}
for (int i = 1; i <= numStar; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
So this is the output I get if I input 4 for numStar
*
**
***
****
There is actually nothing special about nested loops, they behave exactly the same like regular loop.
Specifically here the outer loop loops from i being 1 to numStar and therefore prints numStar rows.
The nested loop loops from j being 1 to i where i is the number of current row being printed. In each iteration it prints one star and therefore altogether it prints i stars.
Therefore here it prints 1 star on row number 1, 2 stars on row number 2, etc.
Try writing down in a paper like this :
i=1 j=1 => *
i=1 j=2 => (j<=i) is false
.
.
i=2 j=1 => *
*
i=2 j=2 => *
**
.
.
You'll get the output if you try to write it in a paper.
In order to understand the nested loop you must understand the for structure. It sounds like you did not get it.
from the basics:
for (int i = 1; i <= numStar; i++) {
System.out.println(i);
}
the code above iterate exactly numStart following the steps:
a-Starts with i=1: int i = 1
b-Test condition: i <= numStar
c-Print the value of i in the screen: System.out.println(i)
d-increments i value: i++
It execute while the conditions is satisfied: i <= numStar. The steps c and d are executed only the condition is satisfied.
the tested loop follows the same logic:
for (int i = 1; i <= numStar; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
when i=1 -> j iterates from 1 to 1. So it prints "*"
when i=2 -> j iterates from 1 to 2. So it prints "**"
when i=3 -> j iterates from 1 to 3. So it prints "***"
and so on...
After the nested iteration finish there is line break: System.out.println();

Printing line of a given matrix

I'm trying to made a method that receives a matrix and prints its lines. For example:
line nb 1 : 3 2 5 6
line nb 2 : 7 9 0 1 4 3
line nb 3 : 3 5 3
I'd like to know why I cannot print the lines of the given matrix using this code. And also, why I cannot increment the variable k, that shows me the number of the line.
When I run this code it does not increment k. It always shows me the number 1 for the line
How can I fix my code?
public static void PrintLine(int[][] matrix){
for (i = 0; i < matrix.length; ++i){ // Loop all long the lines of the matrix
int k = 1; // Number of the line
System.out.print("Line nb " + k + matrix[i]);
k = k+1; // Increment the number of the line by 1
}
}
It's not so much that k does not get incremented; rather, you increment k only to discard it immediately, because the scope of the variable k is restricted to a single iteration (i.e., within the curly braces). The following should work:
for (int i = 0, k = 0; i < matrix.length; ++i, ++k) {
/* work in terms of i and k */
}
which, in your case, simplifies to using i and k for the same purpose:
for (int i = 0; i < matrix.length; ++i) {
System.out.print("Line nb " + i + matrix[i]");
}
Your k variable is initialized inside for loop. It means on each iteration it will be new variable. With initial 1 value.
Move it's itialization out of the loop:
int k = 1; // Number of the line
for (i = 0; i < matrix.length; ++i){ // Loop all long the lines of the matrix
As other have pointed out the scope of your k is incorrect, you can just use the value of i, also when you print your array you are getting the object reference details, you can use Arrays.toString() to print the values from an Array.
for (int i = 0; i < matrix.length; ++i) {
System.out.print("Line nb " + i +": "+ Arrays.toString(matrix[i]));
}

Categories

Resources