Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Code Question

Options
  • 26-12-2006 8:01pm
    #1
    Moderators, Education Moderators, Technology & Internet Moderators, Regional South East Moderators Posts: 24,056 Mod ✭✭✭✭


    Hi all,

    Iv a question regarding code given in this topic;

    http://www.boards.ie/vbulletin/showthread.php?p=2764786

    I didnt want to bump it, so I thought it would be OK to create a new topic asking the question.

    http://www.boards.ie/vbulletin/showthread.php?p=2764786

    The OP wrote this code (I added comments just to see if I understand it right)
    public class Stars
    {
    public static void main(String args[])
    {
    int i, j; // Declare that i and j are both integers. 
    for(i=0; i<10; i++) // for i is equal to 0, is less then 10, increment. 
    {
    for(j=0; j<10; j++) // Same as above but for j
    {
    System.out.print("*"); // print *
    }
    
    System.out.println(); // print new line..
    }
    }
    }
    

    Apparently, that didnt work.. So this solution was given;-
    public class Stars {
    
      public static void main(String args[])
      {
      int i, j; // declare int 1 and j.
      for(i=0; i<10; i++) // for i equal to 10, i is less then 10 - increment.
      {
    
      for(j=0; j<i+1;j++ ) // for j is equal to 0, j is less then i + 1, increment. 
      {
      System.out.print("*"); // print *
      }
    
      System.out.println(); // print line break.
      }
      }
    }
    

    The difference lies in this line I see;
    for(j=0; j<i+1;j++ ) // for j is equal to 0, j is less then i + 1, increment.
    

    But what exactly does it mean? Why are we adding 1 onto i? How do we know what i and j do, we know they are integers but I take it one is for the star and one is for lines.. What states what they are (line or star)?


Comments

  • Registered Users Posts: 9,579 ✭✭✭Webmonkey


    The outer loop goes around 10 times, ie. 10 lines, each time it goes around it prints out an extra star.
    The outer loop, i starts at 0 so instead of printing out zero stars for first line it prints out i+1, (ie 0+1 = 1 star and then exists, goes onto next line and then this time i is 1, so j loop goes around twice and that prints out 2 stars then (1 for each time j loop goes around) and sooo on :)


Advertisement