Easy for Loop Problem

 DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

# Thread: Easy for Loop Problem

1. Registered User
Join Date
Oct 2004
Posts
1

## Easy for Loop Problem

Hello all,

I have stumbled on a programming exercise and am in need of a little help.

Problem: Get an integer n from an input dialog, print out the following pattern on the console window.

For example, when n is 3, there are 5 (2 * n - 1 = 2 * 3 -1 = 5) rows in total:

example: http://david.vonetwork.net/pattern1.bmp

For another example, when n is 4 there are 7 (2 * n -1=2 * 4 -1 = 7) rows in total:

Example 2: http://david.vonetwork.net/pattern2.bmp

I know how to get n from an integer dialog box, but I am stuck in making the patterns. It is required that you use only nested for loops.

The Reward

I am unable to make this a paid project but I am offering 6 g-mail accounts for the correct solution

This should be a simple exercise for any experienced java programming. If you would like to help me out just post the solution either in this thread or in a pm.

Joe

PS. This post is going be posted on multiple forums, first one overall to get the correct solution gets the g0mail accounts. I will of course update you on the status
Last edited by iidavidii; 10-18-2004 at 12:17 AM.

2. Hi,

heres my little effort at it.

Cheers
Graham

----------------------------------------------------------------
Code:
```public class OutputPattern
{

public static void main(String[] args)
{
OutputPattern op = new OutputPattern();
try
{
op.doWork();
}catch(java.io.IOException ioe)
{
System.out.println("Got Exception" + ioe);
}
}

public void doWork() throws java.io.IOException
{
// Assume that this has be read in

int NumberofIterations = Integer.parseInt(System.in.read()+"" ) - 48;

for(int i = 1; i <= (2 *NumberofIterations - 1); i+=2)
{
// Print spacers

for(int spacer=0; spacer < (NumberofIterations - (i/2)); spacer++)
{
System.out.print(" ");
}

// print stars

for(int stars = 0; stars < i; stars++)
{
System.out.print("*");
}
System.out.println("");
}

// Now do it in reverse

for(int i = (2 * NumberofIterations - 3); i >= 1; i-=2)
{
// Print spacers

for(int spacer=0; spacer < (NumberofIterations - (i/2)); spacer++)
{
System.out.print(" ");
}

// print stars

for(int stars = 0; stars < i; stars++)
{
System.out.print("*");
}
System.out.println("");
}
}
}```
Last edited by JGRobinson; 10-27-2004 at 03:59 PM.

#### Posting Permissions

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

 FAQ Latest Articles Java .NET XML Database Enterprise