Results 1 to 3 of 3
  1. #1
    mrjava is offline Member
    Join Date
    Aug 2011
    Rep Power

    Default Nested (for) loops in Java

    Hello. I'm new to Java programming and trying hard to learn it :)
    But these nested for loops where is outer and inner for-loop are giving me headache.

    For example this exercise where app asks user the int value and then prints this star pattern. I've been trying to do this but somehow I don't get a hang of it:

    How many rows:

    ******* (the value is 7 so this prints 7 rows)

    Also different matrix arrays where you are supposed to loop through the array and print values from every element are hard for me.

    Could someone help me at least with that star-pattern exercise and maybe explain what happens in those nested for loops.

    Thank you.

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Voorschoten, the Netherlands
    Blog Entries
    Rep Power


    Take those loops apart: here's a small method that prints 'n' stars:

    Java Code:
    public static void stars(int n) {
       for (int i= 0; i < n; i++) // print n stars
       System.out.println(); // followed by a new line
    Given the small method above, your example can be implemented as follows:

    Java Code:
    for (int j= 1; j <= 7; j++)
    This code also has a nested loop in it, but the inner loop is implemented in another method. Does this clarify things a bit?

    kind regards,

    Build a wall around Donald Trump; I'll pay for it.

  3. #3
    mrjava is offline Member
    Join Date
    Aug 2011
    Rep Power


    I found this code from another forum:
    Java Code:
    for(int i=0 ; i<7 ; i++){
      for(int j=0 ; j<i+1 ; j++){
    I almost got it by myself but that inner loops condition j<i+1, what was wrong in my code. Usually it is always the inner loop what I dont get correct. Outer loop is always looping the number of rows, right?

Similar Threads

  1. Replies: 20
    Last Post: 03-22-2011, 05:02 AM
  2. Nested loops
    By Aestuv in forum New To Java
    Replies: 3
    Last Post: 02-11-2011, 12:40 AM
  3. Nested Loops
    By joemama in forum New To Java
    Replies: 1
    Last Post: 01-01-2011, 10:17 PM
  4. Nested for loops
    By luke in forum New To Java
    Replies: 23
    Last Post: 10-21-2010, 03:49 AM
  5. Nested Loops for Java
    By soccer_kid_6 in forum New To Java
    Replies: 4
    Last Post: 02-21-2010, 06:27 AM

Tags for this Thread

Posting Permissions

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