Why is the this block is not performed during execution? - java

int n = 3;
int x = n;
int y = 0;
for(int i = n; i > 0; i--)
for(int j = 0; j <=n; j++)
if(j > n)
for(int k = 1; k <=n; k++)
System.out.println("x is " +x--);
else
System.out.print("y is " +y++);
under the if statement if(j > n) why is that the for loop is not performed?
i can't really understand why, because our instructor let us analyze the running time and i can't really understand why that for loop is not performed during the execution. please help me..

for(int j = 0; j <=n; j++)
if(j > n)
What you are saying in the for loop is: Execute this code while j is less or equal to n.
Then on the if you say: If j is greater than n.
j will never be greater than n as the for loop limits j falue to be less or equal than n.
That's pretty basic and you should read more on how for works.
Also, avoid not using {}, it's very dangerous. Prefer to always do:
for(int j = 0; j <=n; j++) {
if(j > n) {
....
}
}

Related

Using a counter in bubble sort

The problem is to count how many times my bubble sort algorithm switches the places of numbers. I tried to use a variable which increments by one each time, but I think there may be an error with scopes or something similar. Instead of returning a number such as 6 (which means numbers were swapped 6 times), it returns 0, which is what I initialized my variable as. How would I get my program to work?
public static int sort(int arr[]) {
int length = arr.length;
int temp;
int count = 0;
for (int i = 0; i < (length); i++) {
for (int j = 1; j < (length); j++) {
if (arr[j - 1] > arr[j]) {
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
count++;
}
}
}
return count;
}
Looks like your algorithm is not optimized because of your for loop condition and initialization. As a result you are comparing an element with itself which is redundant.
Proper approach should be like below:
int yourCounter = 0;
for (int i = 0; i < length; i++)
for (int j = 1; j < length-i; j++)
if (arr[j - 1] > arr[j]) {
//swap code
//yourCounter++;
}
your counter should give you proper result then.

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.

How does a for loop increment?

The sum is -9 but i'm having trouble figuring out why. I don't understand how the j-- in the for loop will increment. It should be incremented after the body is executed, right? But doesn't the initialization of the for loop make j-- pointless? So I assume that on the 2nd iteration j becomes 2 because of i++. Could someone help look at this the right way?
public static void whatsTheSum(){
int sum = 1;
int i = 1;
while(i < 5){
for(int j = i; j > 0; j--)
sum += (j - i);
i++;
}
System.out.println(sum);
}
I don't understand how the j-- in the for loop will increment. It should be incremented after the body is executed, right?
It's updated, then, yes. (The update is a decrement, not an increment.) But yes, it happens after each time the loop body is run.
But doesn't the initialization of the for loop make j-- pointless?
No. The initialization has j start with the value from i, and then count down while j is > 0 (without changing i).
So I assume that on the 2nd iteration j becomes 2 because of i++.
The second iteration of the while loop, yes. j will start out at 2 and then the for loop will run twice (for j = 2 and j = 1).
Just for complete clarity, here's how a for loop works:
for (initialization; test; update) {
body;
}
That's executed in this order:
Do initialization
Evaluate test, if false leave the loop
Do body
Do update
Jump to Step 2
To what I understand the requirement stated in the question above to increment j to iterate from 0 to i, you would require something like -
while(i < 5){
for(int j = 0; j < i; j++) {
sum += (j - i);
}
i++;
}
also j++ can be replaced as j=j+1 , j += 1 they would have eht esame effect and the order is very nicely explained by #T.J's answer.
So if you have nested loops its always good to write down each and every iteration:
i = 1, sum = 1
1. while (i < 5) = true so
1.1 for(int j = 1; j > 0; j--) j=1
sum += (1-1)
i=2 sum =1
2. while (i < 5) = true so
2.1 for(int j = 2; j > 0; j--)
sum += (2-2) --> sum = 1
2.2 for(int j = 1; j > 0; j--)
sum += (1-2) --> sum = 0
i=3 sum =0
3. while (i < 5) = true so
3.1 for(int j = 3; j > 0; j--)
sum += (3-3) --> sum = 0
3.2 for(int j = 2; j > 0; j--)
sum += (2-3) --> sum = -1
3.3 for(int j = 1; j > 0; j--)
sum += (1-3) --> sum = -3
And so on

Move left if there is a zero

I am trying to create a program that will take an array of integers, say {2,0,32,0,0,8} that can be of any length, and make it so all of the nonzero numbers are to the left at the lower indexes, and all the zeros are moved to the end.
For example, {2,0,32,0,0,8} becomes {2,32,8,0,0,0}.
This array can be of any length and contain any nonnegative integers.
This is what I have so far:
public static int[] moveLeft(final int[] a) {
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
for (int j = 0; j < a.length; j++) {
if (a[j] == 0) {
a[j] = a[i];
a[i] = 0;
}
}
}
}
return a;
}
However, when I do this, it doesn't work for the first and second characters. If I have {1,2,0,1} it will return {2,1,1,0} when it should return {1,2,1,0}. Any help?
Your inner loop should stop before index i. Change this
for (int j = 0; j < a.length; j++) {
to
for (int j = 0; j < i; j++) {
And then your code works for me.

Transpose a NxN matrix

I have a NxN matrix and it trying to transpose it by this code:
for(int i = 0; i < mat_size; ++i) {
for(int j = 0; j < mat_size; ++j) {
double tmpJI = get(j, i);
put(j, i, get(i, j));
put(i, j, tmpJI);
}
}
it doesn't work, what is the problem? thanks in advance.
It doesn't work since you're swapping the whole matrix with itself. What you need to do is exchange the upper triangle with the lower one:
for(int j = 0; j < i; ++j) {
is one way.
Going from 0 to mat_size will get you reorder the whole matrix two times, getting the original one again.
change to :
for(int i = 0; i < mat_size; ++i) {
for(int j = 0; j < i; ++j) {
double tmpJI = get(j, i);
put(j, i, get(i, j));
put(i, j, tmpJI);
}
}
You need to swap only if j > i. So the inner loop must start at i+1. For j==i (the center diagonal) no swapping is needed, too.
Your solution doesn't work because you're actually swapping twice (once with j=x and i=y and once with j=y and i=x.
For example the (2,5) is swapped for i=2,j=5 and i=5,j=2. Swap twice does nothing.
for(int i = 0; i < mat_size; ++i) {
for(int j = 0; j < i; ++j) {
double tmpJI = get(j, i);
put(j, i, get(i, j));
put(i, j, tmpJI);
}
}
This is because the elements that you swap in the lower triangle of the matrix gets swapped again when the iteration reaches the other side of the diagonal. That is the element is swapped twice which results in nothing.
Try:
for(int i = 0; i < mat_size; ++i) {
for(int j = 0; j < i; ++j) {
double tmpJI = get(j, i);
put(j, i, get(i, j));
put(i, j, tmpJI);
}
}

Categories