Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

For Loop Help

java for loop loop

  • Please log in to reply
4 replies to this topic

#1 welshguy

welshguy

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 14 November 2007 - 06:19 AM

I'm trying to achieve this:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

So far i have written this code:

public static void main(String[] args)
{
for (int rowNumber = 1; rowNumber <= 10; rowNumber++)
{
for (int colNumber = 1; colNumber <= 5; colNumber++)
{
System.out.println("" + rowNumber);

The output I had is as follows:

1
1
1
1
1
2
2
2
2
2
3
3
3
3
3
4
4
4
4
4
5
5
5
5
5
6
6
6
6
6
7
7
7
7
7
8
8
8
8
8
9
9
9
9
9
10
10
10
10
10

Clearly this is wrong & as i'm not a very good Java programmer i'm not sure how to correct this

Any help would be appreciated!
  • 0

#2 v0id

v0id

    Retired

  • Retired Mod
  • PipPipPipPipPipPipPipPip
  • 2313 posts

Posted 14 November 2007 - 08:34 AM

You need to use the value from the first for-loop, in the second as well.
for(int i = 1; i <= 10; i++)
{
    for(int j = 1; j <= i; j++)
        System.out.println(j + " ");
    System.out.println("\n");
}

  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#3 G_Morgan

G_Morgan

    CC Devotee

  • Just Joined
  • PipPipPipPipPipPip
  • 442 posts

Posted 17 November 2007 - 02:47 AM

Personally I'd do something like this


String output = 1;
System.out.println(output);
for(int i = 2; i <=5; i ++{
output = output + " " + i;
System.out.println(output);
}

  • 0

#4 devilsmaster

devilsmaster

    CC Newcomer

  • Just Joined
  • PipPip
  • 20 posts

Posted 30 November 2007 - 09:31 PM

Void is absolutely right

Public static void main(int args[])
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.println("",+j);
}
System.out.print("\n");
}
}


Tha very first line make it to run in the nex line, when loop comes to the J than it will run as many times as the value of i that make it tom run the loops for generating the OUTPUT y ou want. You can even try this code and still if you dont undrstand i can explain it fully.
  • 0

#5 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 30 November 2007 - 09:53 PM

To achieve the exact result you asked for, use devilmaster's code but replace
System.out.println("",+j);

With
System.out.print(j);

  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download