Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Code Question

  • 26-12-2006 07:01PM
    #1
    Moderators, Education Moderators, Technology & Internet Moderators, Regional South East Moderators Posts: 24,071 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, Registered Users 2 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