Seems to be an extra output in nested for loop - java

This code:
for (i = 1; i <= 5; i++)
System.out.print(" i ");
for (j = 1; j <= i; j++)
System.out.print(" j ");
System.out.println();
Gives the following output:
i i i i i j j j j j j
I cannot understand why it gives 6 js instead of 5. Can anyone explain what I am missing?

for applies the increment every time the loop finishes. The condition is checked before beginning the next loop, so i will be 6 instead of 5 by the time your second loop starts.
Fix this by making the second condition j<i instead.

Your first loop's invariant is
i <= 5
therefore the loop will continue to iterate until that invariant no longer holds. So when you reach the second loop, you can be sure that i is not less than or equal 5; in other words, it is greater than 5.

The first loop stops when i failed the condition i <= 5, which means i=6.
So the second loop is exactly as
for (j = 1; j <= 6; j++) System.out.print(" j ");
Which print 6 j.

At the end of the "i for", i equals 6, that's why j is printed 6 times.

Use debug then you will realize this by your won. The moment first for loop exit i=6 and then your second will runs loop runs 6 times since upper limit for j is now 6. Then you get 6 js

The value of i is 6 when it finished the 1st loop. Read more about post increment operator and for loop.

i will be 6 when the j for-loop enters since the first loop would terminate at i==6 and not i==5 as you expect.

Related

Printing the factors of 2-100 in java

I am trying to minimize the iteration so I used j<=i/j in the 2nd for loop. The code is working but I can't get the full output. I mean factors of 6 are 2 and 3, but it is only printing 2.
Can anyone help me? I am a beginner.
class factors{
public static void main (String args[]){
int i,j;
for(i=2;i<=100;i++){
System.out.print("\nFactors of "+i+" : ");
for(j=2; j <= i/j; j++){
if((i%j)==0){
System.out.print(j+" ");
}
}
}
}
}
After:
System.out.print(j+" ");
Add:
System.out.print((i/j)+" ");
The point of iterating until i/j is because the factors come in pairs, j and i/j, and you only need to iterate over half of them, and the others can be calculated from the ones you find.
You get an unexpected output because i/j will be evaluated every iteration of the loop.
When j=2, i/j is 3, so the condition is true, and the first iteration of the loop runs. The next iteration, j=3, i/j is 2, which less than j, the condition is false, so the loop terminates there, without running the second iteration.
I think what you meant to say is i / 2. So change i/j to i/2.
for(j=2; j <= i/j; j++)
Let run the code for i=6
So first it intialize j to 0 and then
J<=6/2 so it it true because 2<=3
But on next iteration
J=3 and then
J<=6/3 in this it is not true because 3<=2
So change the condition.
for(j=2; j <= i/j; j++){
if((i%j)==0){
System.out.print(j+" ");
}
}
There are two problems in this code.
First, you only print one factor (j) when you find pairs (both j and i/j). Already mentioned here.
Second, fixing that by printing j and i/j breaks the result for perfect squares, where j and i/j are the same (equal). It prints the square root as a factor twice. To fix that, you can stop the loop before you test a perfect square. Then you can test for that special case outside the loop.
for (j = 2; j < i/j; j++) {
if ((i%j) == 0) {
System.out.print(j + " " + i/j + " ");
}
}
if (j * j == i) {
System.out.print(j);
}
Another alternative would be to check if j and i/j were equal before printing i/j. Something like
System.out.print(j + " ");
if (j != i/j) {
System.out.print(i/j + " ");
}
But that requires more checks than is necessary, because equality will only happen once per the loop. But you have to check once for every factor pair that you find.

How does that for loop doesn't goes out of bounds with unidimensional array in JAVA?

Take a look :
int[] v = new int[10];
for (int i = 0; i < v.length; i++) {
for (int j = i + 1; j < v.length; j++) {
if (v[i] > v[j]) {
aux = v[i];
v[i] = v[j];
v[j] = aux;
}
}
}
This works perfecly. But can someone explain how?
How this array DOES NOT goes out of bounds even if I start j with i + 1 ? How does this works?
You have confused the initialization with condition. The syntax for for loop() is-
for(initialization; condition; updation)
{
statement(s)
}
So even if you start j from 1 ( j = i+1 and initial value of i = 0), j will update only till it is equal to the length of the array v i.e., 10. So the moment, j = 10 ( when i = 9), the control will come out of j for loop() and when it will transfer to i for loop(), i will be updated to 10, thus meeting it's condition and moving the control out of i for loop() also.
I think you need to go back to basics on for loops
a for loop can be defined as for(before starting;continue when true;do at end of pass))
So it doesn't matter what your start value is, as soon as j is equal to v.length it will stop. It just does 1 less loop that if you started at i.
Your for loops are made up of a variable to keep track, the condition and the iteration. In your code, the condition of the for loops states that the variable that is keeping track cannot go past the length of v. Therefore, during the sort (because that's what the code is), the inner loop compares all of v's values using j as the index to swap if they meet the if condition. The outer loop is just there to make sure that each index of v is checked and are in the right place.

Printing Simple Patterns in Java

Could someone explain the basics behind printing simple patterns in Java?
I'll give one specific example.
I'd just like for someone to clarify what each line is doing so I get a better understanding of how this works. Any other explained examples (line by line) would also be appreciated!
public static void drawPyramidPattern() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5 - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
Printing anything or everything via a loop is just about understanding the flow of execution. In your code also, if you'll start watching the flow line by line you'll come to know that how it is working exactly.
If you understand how it works, you would be able to print any pattern, but basics should be clear. Try printing variable i, j and k values after each iteration. See the values that how that gets changed after each cycle of execution and then see the logic you've applied.
Your question is somewhat very broad in scope and can not be answered exactly unless narrowed it down. I would suggest to run this line by line and watch the output, try more changes even if it doesn't make any sense, you'll be having a good understanding over looping even for all of your future tasks. And if after trying yourself, you come to any problem, share here, people are ready to solve them. :)
Hope this helps.
First you must a have complete understanding of loops, nested loops then you come up to patterns designing.
1) First run the loops in hard form like on Register/on Page for understanding the loops.
2) Use debugger to identify the loop progress.
If you think about it in terms of mathematics, loops are just functions.
A single for loop would just be x.
Example
for (int i = 0; i < 5; i++) {
System.out.println("This is function x.");
}
However when you start nesting loops it because a greater function. A for loop inside another for loop would be a function x^2
For example:
for (int i = 0; i < 5; i++) {
for (int j = 0; J < 5; j++){
System.out.println("This is the j loop");
}
System.out.println("This is the i loop");
}
The reason behind this is because in order to finish the first iteration of i, everything inside the loop must be completed. But, the i loop has another loop inside of it, so that must be finished first. So the loop with j must execute until it is finished. (In this case 5 times), Great, now we can increment i. But now we have to step through j again! This process continues until i reaches its threshold of being < 5. So the output would look something like this
Output:
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the i loop
This is the j loop
This is the j loop
....
This would continue until the i has reached 5, in which case it no longer satisfies the necessary i < 5, and the loop would end. Hopefully this helps
First, since i = 0 & 0<5 is true you enter the first(outer) for-loop.
Remember i = 0.
Then j = 0; but 0 < i = 0 is false so you don't enter the second loop.
For the third loop, k = 0 & 0<=0 is true. So you enter the loop and execute the print statement, i.e print a star.
k++, this will increment k by 1 and check the boolean; You ask yourself is 1 <= 0; clearly no ; so you exit the for-loop and then reach the println statement which will take you to the next line.
And then you go back to the outer loop.
//this code print Diagonal Pattern if matrix is
1 2 3
4 5 6
7 8 9
output is :
1
4 2
7 5 3
8 6
9
import java.util.*;
class DiagonalPattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x[][];
int i,j,row,col,p,temp=1,last=0;
System.out.println("how many array wants to create and size of array");
row=sc.nextInt();
col=sc.nextInt();
x=new int[row][col];
System.out.println("Enter " +row*col+ " elements of array of array");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
x[i][j]=sc.nextInt();
last=j;
}
}
for(i=0;i<row;i++)
{
System.out.println("");
int k=i;
for(j=0;j<=i;j++,k--)
{
if(j==col)
{
break;
}
else
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
for(p=x.length;p>0;p--,temp++)
{
System.out.println("");
i=x.length-1;
int k=i;
for(j=temp;j<=last;j++,k--)
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
}

Finding value of 'i' in a for loop?

I have this question here:
What is i after the following for loop?
The given code is:
int y= 0;
for (int i= 0; i<10; ++i)
{
y+= i;
}
I put that the answer is 9, but that is incorrect according to the grader. I even printed 'i' and it came out as 9.
The answer is that i is undefined after the loop. It is 9 at the last iteration, though.
Value of i would be 10. As of now, if you try to print the value of i outside the loop, i is undefined.
When i was 9, you continued with the loop, for next iteration i became 10 and condition fails and causes to break the loop. So value of i is 10. Keep it in mind having stpe statement as ++i or i++ is not different w.r.t the values that i would attend. step statement always executes before start of the next iteration.
Following small change would help you to prove the output.
int i,y= 0;
for (i= 0; i<10; ++i)
{
y+= i;
}
printf("%d\n",i);
That being said if you are printing the value of i within the loop, then you'll get maximum value of i as 9 on the output. Probably this is what you were doing to conclude the answer as 9.
int y= 0;
for (int i= 0; i<10; ++i)
{
y+= i;
printf("%d\n",i);
}
Think of it this way. Using y+=i is constantly adding the current value of y to the value of i. So, in turn, you're not getting the true value of i, but rather the cumulative value.
This is what is actually happening in y+=i
1+2+3+4+5+6+7+8+9
Also, just printing out i after the loop would be invalid since outside that for loop, i no longer exists.
You could just do this:
int y=0;
for(int i = 0; i<10;i++)
y=i;
System.out.println(y);

Reverse printing of an array

(Java beginner)
I came up with a code that would display an int array in reverse and although I know there's probably a better way to do it, I think this logic should work:
for(int i = 0, j = numList.length - 1; i < j; i++, j--)
{
int temp = numList[i];
numList[i] = numList[j];
numList[j] = temp;
System.out.print("Reverse order: " + temp + " ");
}
What I don't understand is that when I enter 5 numbers, the console only shows the first two numbers and it ends there:
1
2
3
4
5
Reverse order: 1 2
What's wrong here and what can I do to fix it?
That code is just faulty. Use this instead.
for(int i = numList.Length - 1; i >= 0;i--)
{
int temp = numList[i];
System.out.print("Reverse order: " + temp + " ");
}
In your code, you increment i and decrement j, meaning that if you'd loop untill your condition is satisfied, you'd get about half the loop done. Try and create a table of the values of your loop step by step, you'll see what I mean :)
i++ and j-- along with the loop iteration condition of i < j would become false when i and j reach the middle of the array. So essentially your for loop is only working up the first half of the loop. I didnt run you code but this is the first observation i made.

Categories