Results 1 to 3 of 3
Thread: Nested (for) loops in Java
- 08-29-2011, 12:13 PM #1
Member
- Join Date
- Aug 2011
- Posts
- 2
- Rep Power
- 0
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:
7
*
**
***
****
*****
******
******* (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.
- 08-29-2011, 12:27 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,392
- Blog Entries
- 7
- Rep Power
- 17
Take those loops apart: here's a small method that prints 'n' stars:
Given the small method above, your example can be implemented as follows:Java Code:public static void stars(int n) { for (int i= 0; i < n; i++) // print n stars Sytem.out.print('*'); System.out.println(); // followed by a new line }
This code also has a nested loop in it, but the inner loop is implemented in another method. Does this clarify things a bit?Java Code:for (int j= 1; j <= 7; j++) stars(j);
kind regards,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 08-29-2011, 12:35 PM #3
Member
- Join Date
- Aug 2011
- Posts
- 2
- Rep Power
- 0
I found this code from another forum:
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?Java Code:for(int i=0 ; i<7 ; i++){ for(int j=0 ; j<i+1 ; j++){ System.out.print("*"); } System.out.println(); }
Similar Threads
-
[Semi-Beginner] (nested loops) What's wrong with my code? (nested loops)
By Solarsonic in forum New To JavaReplies: 20Last Post: 03-22-2011, 04:02 AM -
Nested loops
By Aestuv in forum New To JavaReplies: 3Last Post: 02-10-2011, 11:40 PM -
Nested Loops
By joemama in forum New To JavaReplies: 1Last Post: 01-01-2011, 09:17 PM -
Nested for loops
By luke in forum New To JavaReplies: 23Last Post: 10-21-2010, 02:49 AM -
Nested Loops for Java
By soccer_kid_6 in forum New To JavaReplies: 4Last Post: 02-21-2010, 05:27 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks