How do I read a loop that has no braces? - java

I'm trying to read the output of this code, but it simply just doesn't make sense to me.
Even after learning that a loop without braces only loops through the first line, the output still makes no sense, at all. Some numbers do, but others just don't.
My code:
int n = 8;
int i = 1;
int j = 1;
j = n + 2;
System.out.println (n + " " + i + " " + j );
while (n > 1)
{
n = n/2;
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
j++;
}
System.out.println (n + " " + i + " " + j );
And it outputs:
8 1 10
4 2 10
4 4 10
2 2 11
1 2 13
I get the 8-1-10
and the 4-2-10
but anything after that, I'm stumped, I don't get how the computer calculates the rest.
Would someone mind going through the rest of the output with me, step by step?
Thank's in advance.

No braces means that the loop affects only the next statement that follows the loop.
So
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
is equivalent to
for (i = 2; i <= n; i = i+2)
{
System.out.println (n + " " + i + " " + j );
}
Usually, indentation is used in those cases to make the code more comprehensible, like this:
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
EDIT: Now, this is the actual answer to the question. It all depends on the different iterations the loop does and how do the variables get incremented.
int n = 8;
int i = 1;
int j = 1;
j = n + 2; //This means that j takes the value 10.
System.out.println (n + " " + i + " " + j ); // 8 1 10 So far, so good.
Now, on with the iteration:
while (n > 1)
{
n = n/2;
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
j++;
}
For the first iteration, we have n=8 i=1 j=10, so since n > 0 is true the loop takes place.
n = n / 2; //n = 4
Then, the for (note that it just assigns the value 2 to i):
for (i = 2; i <= 4; i = i+2) //Since n = 4
Since n = 4, the only values that i can take are 2 and 4, then the prints are:
4 2 10
4 4 10
After that, j is incremented by one, making it j = 11. The condition for the while is met again because n = 4. n = n/2 makes n take the value 2, so it enters the while again. Let's take a look at the for again:
for (i = 2; i <= 2; i = i+2) //Since n = 2
This time, the only value that i can take is 2 (note that the value of i is reset again to 2 while starting the iteration), and that's the print you get.
2 2 11
Before iterating again, j++ makes j have the value 12.
On the final iteration, n = n/2 results in n = 1 since n is an int but this is done inside the while, so it enters again. Now that n = 1 the loop looks like this:
for (i = 2; i <= 1; i = i+2) //Since n = 1
i is set to 2 and the condition for the for is not met (2 <= 1 is false). Then there is no print this time, yet j is incremented to 13 at the end of the while.
In the next iteration you have n = 1, that means that the while's condition is not met so the iteration breaks. Finally you have n = 1, i = 2 and j = 13. That's the last print you get.

You start the while loop with n = 8, i = 1 and j = 10.
start while: (n=8 > 1) is true
n = 4
i = 2 (i <= 4, so do for loop, then change i to i+2=4)
print 4,2,10
i = 4 (i <= 4, so do for loop again, then i = i+2 = 6
print 4,4,10
i = 6 (i <= 4 is false, so exit for)
j++ so j becomes 11
next while:
n = n/2 = 2
i = 2 (i <= 2, so do for loop, then change i to i+2=4)
print 2,2,11
i = 4 (i <= 2 is false, so exit for)
j++ -> j = 12
next while:
n = n/2 = 1
i = 2 (i <= 1 is false, so exit loop)
j++ -> j = 13
exit while.
Final print= n = 1, i = 2 (value assigned in last for loop, loop doesn't get executed so i doesnt get incremented by 2), and j = 13
Hope this helps :)

Related

Non Recursive Merge Sort With 2 Array List

I'm trying non-recursive Merge Sort with 2 Arrays, But it doesn't work when given array's size is not 2^n.
It works fine when the given array's size is 2^n.
For example, given array which's size is not 2^n : 7 2 9 11 4 3 8 6 1 10
As step is 1, sort result is :
2 7 9 11 3 4 6 8 1 10
And now it will sort with 4 items, 4 items, 2 items.
But it doesn't work.
so I checked the console, and it seems like, the problem is
while(leftStart <= leftLast && rightStart <= rightLast).
As I catched, when checking 2 7 9 11 and 3 4 6 8 to sort, the leftStart is going to higher than leftLast, 2 < 7 (leftStart++), 2 < 9 (leftStart++) so leftStart > leftLast, the while loop is broken ).
It should check for the others, because it could be L1.get(leftStart) > L1.get(rightStart)
But I don't know how to solve this problem..
Thank you for your help.
public statid void main(String[] args){
ArrayList<Integer> l = new ArrayList<>();
l.add(7);
l.add(2);
l.add(9);
l.add(11);
l.add(4);
l.add(3);
l.add(8);
l.add(6);
l.add(1);
l.add(10);
sort(l);
}
public static void sort(ArrayList l) {
L1 = null;
L2 = null;
step = 1;
L1 = l;
L2 = new ArrayList<>();
for(int i = 0; i < L1.size(); i++)
L2.add(null);
int tSize = l.size();
while(step <= l.size() ) {
for(int i = 0; i < tSize; i += this.step*2) {
int leftStart = i;
int leftLast = (leftStart + this.step)-1;
if(leftLast >= tSize-1)
continue;
int rightStart = i + this.step;
int rightLast = (rightStart + this.step)-1;
if(rightStart >= tSize)
rightStart = tSize - 1;
int idx = i;
// System.out.println("step : " + step + " || idx : " + idx + " || leftStart : " + leftStart + " || rightStart : " + rightStart);
// System.out.println("step : " + step + " || idx : " + idx + " || leftEnd : " + leftLast + " || rightEnd : " + rightLast);
// System.out.println();
while(leftStart <= leftLast && rightStart <= rightLast) {
System.out.println("leftStart : " + leftStart + " || rightStart : " + rightStart + " || idx : " + idx);
Object a = L1.get(leftStart);
Object b = L1.get(rightStart);
if(comp.compare ( a, b ) < 0 ) {
L2.set(idx++, L1.get(leftStart++));
L2.set(idx, L1.get(rightStart));
}else {
System.out.println("idx :::: " + idx);
L2.set(idx++, L1.get(rightStart++));
L2.set(idx, L1.get(leftStart));
}
}
}
for(int i = 0; i < L1.size(); i++) {
L1.set(i, L2.get(i));
}
System.out.println("============================");
for(int j = 0; j < L1.size(); j++) {
System.out.print(L1.get(j) + " ");
}
System.out.println("\n============================");
step *= 2;
}
}
The result:
1 2 3 4 6 7 8 9 8 10
If an array has an odd number of items, then splitting it will result in one subarray will have one more item than the other.
[2,7,9,11,3,4,6,8,1,10]
/ \
[2,7,9,11,3] [4,6,8,1,10]
/ \ / \
[2,7,9] [11,3] [4,6,8] [1,10]
/ \ / \
[2,7] [9] [4,6] [8]
Both recursive and non-recursive merge sort have the same time complexity of O(nlog(n)).
The iterative version doesn't use recursion to split the array. Rather, it uses nested loops.

How verify that 3 numbers in sequence are equals? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I have to check if a sequence of any numbers are equals. The user will submit a sequence, and if, the numbers repeat in sequence, he won some points.
And the sequence to win the points it's a sequence of three. For example:
1 3 4 4 4 5
He won the points because he inputted a sequence of 3 numbers 4.
The sequence of numbers it's on a Vector. The size of the vector, It's given by the user too.
for (int i = 0; i < M.length; i++) {
if (M[i] == M[i + 1] && M[i + 1] == M[i+2]) {
if (L[i] == L[i + 1] && L[i + 1] == L[i + 2]) {
ValuePoint = 0;
} else {
PExtraM = i;
ValuePoint = 30;
}
Scanner sc1 = new Scanner(System.in);
R = sc1.nextInt();
int M[] = new int[R];
int L[] = new int[R];
for (int i = 0; i < M.length; i++) {
M[i] = sc1.nextInt();
}
for (int i = 0; i < L.length; i++) {
L[i] = sc1.nextInt();
}
//The problem It's here ************************************
for (int i = 0; i < M.length; i++) {
if (M[i] == M[i + 1] && M[i + 1] == M[i+2]) {
if (L[i] == L[i + 1] && L[i + 1] == L[i + 2]) {
ValuePoint = 0;
} else {
PExtraM = i;
ValuePoint = 30;
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at maratona.Maratona2.main(Maratona2.java:37)
Java Result: 1
i < M.length
Now let's assume the length of the Vector you are saying is 5 ok?
Now my loop will run till i is less than 5, right?
Now go to your next code :
if (M[i] == M[i + 1] && M[i + 1] == M[i+2])
Let's take the value of i as
4 (suppose)
which is in fact less than 5 and the loop condition satisfies.
But see the next code, it becomes
M[4]==M[5]&& ==M[6]
Obviously since the length of the given Vector is 5, my last element's index will be 4.
So after that **5 & 6 ** will show null only.
That's why it's saying ArrayIndexOutOfBounds Exception error at 5.
Hope this helps!
your loop variable i must stop at m.length-3
(i <m. length-2)
to have i+1=m.length-2 and i+2=m.length-1
but in your case you are trying to access i+1=m.length and i+2= m.length+1 both are out of bounds on the last two iterations
As the others already said, u r overshooting the boundaries of your array. You need to stop the loop 2 earlier to prevent.
You possably want to use something like that:
int sequenceLength = 3;
for (int i = 0; i <= M.length - sequenceLength; i++) {
boolean correct = true;
for (int j = 0; j < sequenceLength && (correct = (M[i] == M[j+i])); j++);
if (correct){
ValuePoint = 0;
} else {
PExtraM = i;
ValuePoint = 30;
break;
}
}

Can someone explain how this left rotating array code works?

I am trying to learn more about arrays and how to rotate them. I stumbled upon a code and I'm trying to figure out how it prints out the rotation correctly.
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
int d = sc.nextInt();
int arr [] = new int [n];
for (int i = 0; i < n; i++)
{
arr [i] = sc.nextInt();
}
for (int i = 0; i < n; i++)
{
System.out.print (arr [(i + d) % n] + " ");
}
}
I have tried doing the math myself to see how it works, but it doesn't add up and I'm not sure what I'm doing wrong. The n is for the number for integers in the array and d is the number of rotations.
The equation is: (i + d) % n with n = 5, d = 4, and the array being {1,2,3,4,5}
(1 + 4) % 5 = 5 % 5 = 0
(2 + 4) % 5 = 6 % 5 = 1
(3 + 4) % 5 = 7 % 5 = 2
(4 + 4) % 5 = 8 % 5 = 3
(5 + 4) % 5 = 9 % 5 = 4
The answer that it prints out is 5 1 2 3 4 which is correct, but from what I calculated it should print out as 1 2 3 4 5. How I got this is that from the following calculations it says that 1 should go to index 0, 2 should go to index 1, etc... If you guys can help explain how the code works, that would much appreciated.
Here,
for (int i = 0; i < n; i++)
{
System.out.print (arr [(i + d) % n] + " ");
}
The array will start from 0 since in the for loop you gave i as 0. so it will start from 0 to 4.
(0 + 4) % 5 = 4 % 5 = 5
(1 + 4) % 5 = 5 % 5 = 1
(2 + 4) % 5 = 6 % 5 = 2
(3 + 4) % 5 = 7 % 5 = 3
(4 + 4) % 5 = 8 % 5 = 4
First, you collect arrays with the contents {1,2,3,4,5}, this means you have 5 indexes with details :
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
Then you want each index content to be added to the value d then modulus % with the value n.
What's wrong is in your second iteration ?
for (int i = 0; i < n; i++){
System.out.print (arr [(i + d) % n] + " ");
}
If you print this (i + d)% n, it will produce this :
(0 + 4) % 5 = 4
(1 + 4) % 5 = 0
(2 + 4) % 5 = 1
(3 + 4) % 5 = 2
(4 + 4) % 5 = 3
So with this command :
System.out.print (arr [(i + d) % n] + " ");
Actually you are printing :
arr[4]
arr[0]
arr[1]
arr[2]
arr[3]
So if you want the results that you want, change the second iteration by holding the value of each index of your array with the following code:
for (int i = 0; i < n; i++){
arr[i] = (arr[i] + d) % n;
System.out.print(arr[i] + " ");
}
This will print 0 1 2 3 4
Hope this helps

Need guidance with loops and multiples

This is my code so far. It prints the numbers 0 through 10. But I can’t figure out how to multiply each number by 2 and 10.
while(numberCounter <= 9){
System.out.println("Number: " + numberCounter);
numberCounter++;
}
Well, what you are doing is probably better suited for a for loop. Like this:
for (int i = 0; i < 10; i++) {
System.out.println("Number: " + i); // This prints 0-9
}
Or for each number times 2:
for (int i = 0; i < 10; i++) {
System.out.println("Number: " + (i*2)); // This prints 0-9 times 2
}
Or for each number times 10:
for (int i = 0; i < 10; i++) {
System.out.println("Number: " + (i*10)); // Prints 0-9 times 10
}
Lastly, each number times 10 times 2:
for (int i = 0; i < 10; i++) {
System.out.println("Number: " + (i*10*2)); // Prints 0-9 times 10 times 2
}
You should take a class on Java or read a thorough tutorial or book, because these are very basic Java topics. Try this one: http://www.learnjavaonline.org/

Why does this statement print this output?

Why does this print statement print 3 and not 1004 as the output?
int n = 2005;
for (int i = 0; i < 50; i++)
n = (n + 3) / 2;
System.out.print(n);
if I do this:
int n = 2005;
for (int i = 0; i < 50; i++)
System.out.println(n);
n = (n + 3) / 2;
System.out.print(n);
It prints 2005 for each iteration and 1004, for the last time.
If there was brackets (like below)
int n = 2005;
for (int i = 0; i < 50; i++){
System.out.println(n);
n = (n + 3) / 2;
}
System.out.print(n);
}
then it behaves like 2005
1004
503
253
128
65
34
18
10
6
4
3
3....3
Print n inside the for loop then you will got how this work.
int n = 2005;
for (int i = 0; i < 50; i++){
System.out.println(n);
n = (n + 3) / 2;
}
Without going into detail: You are more or less cutting n in half every time. Eventually n will approach 3. Then its (3 + 3) / 2 == 3. In fact, you would get there for most initial numbers given a long enough iteration.

Categories

Resources