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.
Related
I'm currently struggling understanding this loop:
class Test{
public static void main(String args[]){
int i=0, j=0;
X1: for(i = 0; i < 3; i++){
X2: for(j = 3; j > 0; j--){
if(i < j) continue X1;
else break X2;
}
}
System.out.println(i+" "+j);
}
}
So far I know that the values of the variable will be:
0 3
1 3
2 3
and finally will print 3 3.
After the third iteration the condition on X1 will be false resulting in an interruption of the loop statement. While it's clear to me why the value of i is equal to 3, I do not understand why the value of j is 3 as well. Initially the value of j is 0, when we enter in the loop is 3, but in the last iteration we do not enter really in the X2 loop, since i<3 evaluate false. So the question is why the compiler "save" the value of k ? And even if the compiler save the value of j from the previous iteration should be 2 ...
j-- is dead code here and will never be reached. Think about how the code works for a moment here:
X2: for(j = 3; j > 0; j--){
if(i < j) continue X1;
else break X2;
}
If one situation you continue to the outer loop, in the other situation you break out of this loop. This loop actually never even goes past a single iteration so you might as well just write this like this:
int i=0, j=0;
X1: for(i = 0; i < 3; i++){
j = 3;
if(i < j) continue X1; //This line does nothing at this point as well since the loop will iterate anyway
}
This is exactly the same as your current code, which clearly shows j will stay at 3.
for(j = 3; j > 0; j--)
You are setting j=3. j-- is not run until the next j loop, that never occurs, so it cannot be 2.
else break X2;
and
j--
are never being reached.
'i' can never be 3 within the loop since the outer loop's condition is i < 3, and therefor the inner loop can only perform
if(i < j) continue X1;
since 'j' always starts at 3 and i <= 2. is always true. So 'j' never changes value, and the outer loop breaks when i = 3, resulting in, "3 3".
i j
0 3
1 3
2 3
break occurs;
print i + j;
Initially the value of j is 0, when we enter in the loop is 3, but in the last iteration we do not enter really in the X2 loop, since i<3 evaluate false. So the question is why the compiler "save" the value of k ?
j is declared at the first line in main. This means that it will remain in scope and retain any modifications until main ends and the variable is destroyed.
And even if the compiler save the value of j from the previous iteration should be 2.
As you said above, the value of j from the last iteration of the loop was 3 not 2. When you continue X1 the j-- was never executed.
It is because of the dead code as others mentioned. You should debug your program by going step by step I don't know which IDE you are using but it probably provides this feature.
However, I want to advice you to not use continue and break statements. It is highly discouraged by the instructors. They cause spaghetti programming and confusions like you have.
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.
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.
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();
This may seem silly, but I'm a bit confused about the following code:
public class Loops{
public static void main(String[] args) {
int i = 0;
int j = 2;
int k = 0;
boolean continue = i<j;
while (continue && k < 2) {
i++;
j--;
k++;
}
System.out.println(j);
}
}
This program prints 0, but I just don't understand why it doesn't print 1. The way I see it, after one loop i = j = 1. And thus continue = false. So if anyone can explain to me the logic behind this I would greatly appreciate it!
continue does not reevaluate itself after every loop iteration because he is defined outside of the loop.
instead, check in the loop condition for i < j
while (i<j && k < 2) {
i++;
j--;
k++;
}
Your loop would be optimized by compiler as:
boolean continue = i<j;
while (true && k < 2)
and finally
while (k < 2)
So it need to loop two times to exit
After the first loop: j == 1, k == 1
After the second loop: j == 0, k == 2, exit now
this is why finally j == 0
Try out putting condition inside a while():
while (i<j && k < 2)
Continue is only set outside of loop body, it is never updated during the loop. Thus continue is set to true before the loop starts and then never modified again.
First of all, your continue variable always evaluates to true (0 < 2) so we can ignore it.
First iteration:
i ends up evaluating to 1.
j ends up evaluating to 1.
k ends up evaluating to 1.
As k < 2, we do another iteration.
Second iteration:
i ends up evaluating to 2.
j ends up evaluating to 0.
k ends up evaluating to 2.
As k == 2, we exit the loop.
Then we print j, which evaluates to 0.
You only set the value of variable 'k' once and consequently continue as well. You need to re-evaluate the conditional expression inside the loop as well.
That said, I would suggest you refrain from using 'continue' as a varible name; I'm fairly certain it is a reserved word in many languages.