-8

I am trying to do exactly what the title says. I have no clue how to begin this code other than the knowledge that it will most likely have to have a do-while loop with a body inside the 'while' portion enclosed in braces. I would like to understand this rather than get a straight answer, so if you could either write a code and explain or give more hints at how to do it that would be greatly appreciated! The output needs to look like this:

1 (new line)
1 3 (new line)
1 3 5 (new line)
.. ... (new line)
.. ... ... (new line)
1 ... ... 999997 (new line)
1 ... ... 999997 999999 

(It is not letting it show that it increases by 1 odd number each line, so i denoted with "(new line)" I hope it is more readable now.)

OK, thanks to newproducts clarification i was able to write this:

    String line = "";
    int start = 1;

    for(;start <= 999999;)
        do{
            System.out.println(line);
            start += 2;
            line += " "  + start;
            }
        while(start <= 999999);

But i face a small problem, 1 does not appear at the start of any of the lines. What am I forgetting to do?

**RESOLVED. I added 1 + line to my print statement and it runs the way I want. Thank you to everyone who tried to help, especially newproduct who new what I needed even with me not wording my question properly.

4

3 回答 3

1

You can think of the problem as the following:

each progressive line includes the content of the previous line plus another odd number. Therefore, it would make a lot of sense to always store the content of the previous line under a String variable, perhaps.

Now to find every odd number, start with the number 1 and add 2 each time until a given number (in this case 9999999999) is surpassed. The same thing can be done with evens -- you simply start with 2 instead of 1.

In a do-while loop structure, it would look something like this (pseudocode):

int lastnum = 1;
String prevLine = lastnum;

do while loop (999999 not passed)
{

    PRINT(prevline + " " + (lastnum + 2));

    lastnum += 2;

    \\update the information stored in the previous line
    prevLine += " " + lastnum;

}

In essence you want to:

1) Start with 1. 2) Print the previous line + the new number (for the first number, the previous line will be blank). 3) Update the previous line 4) Continue steps 2-3 until 999999999 is passed.

于 2013-07-16T19:12:39.757 回答
0

you can use a for loop to get you started

Here's a sample of a 4 loop that counts odd numbers from 1 to 999 inclusive

int n = 999;

for(int i=1; i<= n; i+=2)
{

}

maybe you can try putting one for loop inside another and see if that does it for you.

于 2013-07-16T18:56:32.473 回答
0

You can adopt the progression approach, that stores the previous results and adds one more to it thereby creating the result for next line because calculating same thing for every line is not a good idea.

于 2013-07-16T18:57:48.277 回答