Results 1 to 3 of 3
  1. #1
    Palindrome5 is offline Member
    Join Date
    Oct 2012
    Posts
    5
    Rep Power
    0

    Default Not sure what this particular for loop is doing

    I do not understand lines 18-21 of the following code. How is j changing value in the for loop that involves k? The only way I could see that happening is if the k loop were nested in the j loop, which it clearly isn't.

    Java Code:
    import java.text.*;
    import java.util.*;
    
    public class HelloWorld
     {
     public static void main(String[] args)
     {
    
    	//loop iterator
    	 int i,j,k;
    	 //output the upper triangle, line by line, space first, and then "*"
    	 for (i=1;i<=3;i++)
    	 {
    		 for (j=0;j<3-i;j++)
    		 {
    			 //System.out.print(' ');
    		 }
    		 for (k=1;k<=5-2*j;k++)
    		 {
    			 //System.out.print('*');
    		 }
    		 System.out.print('\n');
    	 }
     
    	//output the lower triangle, line by line, space first, and then "*"
    	//***
    	// *
    	for (i=1;i<=2;i++)
    	{
    		for (j=1;j<=i;j++)
    		{
    			System.out.print(' ');
    		}
    		for (j=1;j<=5-2*i;j++)
    		{
    			System.out.print('*');
    		}
    		System.out.print('\n');
    	}
    	 
     }
     }

  2. #2
    JBelg is offline Member
    Join Date
    Oct 2012
    Posts
    36
    Rep Power
    0

    Default Re: Not sure what this particular for loop is doing

    The j in the for loop mentioned is not a local to the for loop, it's declared outside of it, so every time the j changes, its value is stored outside of it and it can be used in other loops.

    I hope you understand and if I only raised more questions feel free to ask them.

  3. #3
    Palindrome5 is offline Member
    Join Date
    Oct 2012
    Posts
    5
    Rep Power
    0

    Default Re: Not sure what this particular for loop is doing

    On the contrary, that explains it beautifully. Thank you!

Similar Threads

  1. Converting a for loop to a do-while loop
    By awesom in forum New To Java
    Replies: 1
    Last Post: 11-23-2011, 03:02 PM
  2. Replies: 2
    Last Post: 11-07-2011, 02:25 AM
  3. Replies: 1
    Last Post: 10-01-2011, 02:12 AM
  4. JTextField loop 2x for-loop WEIRD!
    By Streetproject in forum AWT / Swing
    Replies: 2
    Last Post: 02-16-2011, 05:46 PM
  5. Replies: 5
    Last Post: 04-30-2010, 05:05 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •