• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

java- nested "for" loops

quietRiot

[H]ard|Gawd
Joined
Jul 3, 2003
Messages
1,109
Im trying to come up with a simple set of nested for loops to print the following.

123456789
2345678
34567
456
5


This isn't an assignment or anything, im just having fun with loops!

This is how im thinking..

3 for loops

loop 1) controls the beginning
loop 2) controls the ending
loop 3) controls the middle

im having a hard time wrapping my brain around the concept of 3 nest for loops though... 2 is easy! :p

any suggestions? i dont necessarily want the hard code on here, i just need some help with the strategy
 
Your best bet would be to stick those numbers in an array, for one.
 
This can be done with just two loops. With the outer loop, use a variable for the upper bound(set its value before entering the loop). You can then decrement that value at each iteration as well as incrementing the lower value. For example:
Code:
for (int i = 1; i<j--; i++)
Then the inner loop prints out the appropriate values for each line.

It could be done with three loops, but I see no reason to do it that way. One loop would increment the lower bound and the next inner loop would decrement the upper bound. The innermost loop would print the values for each line.
 
SpeedRunner said:
Your best bet would be to stick those numbers in an array, for one.
Stick what numbers in an array? All he needs is a beginning lower bound and a beginning upper bound.
 
You could do it with one for loop or as many for loops you felt like writing. Read in 123456789 as a String ( or int and convert to string or vis versa). Then use substring to take the front and last one off. then increase x and decrease y each time you print it ie. str.substring(x, y);
 
Code:
String foo = "123456789";
for(int i = 0; i <= foo.length()/2; i++)
{
  System.out.println(foo.substring(i, foo.length()-i));
}
 
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#substring(int,%20int)

Here's an entry on substring, for those (like me) that haven't used it before.
 
generelz said:
Code:
String foo = "123456789";
for(int i = 0; i <= foo.length()/2; i++)
{
  System.out.println(foo.substring(i, foo.length()-i));
}

I have to hand it to you, this a flat out nice little alg.
 
going back to the array suggestion, could i not stick 1,2,3,4,5,6,7,8,9 in a 1d array, running a loop to cut off the first and last numbers, printing each time?
 
quietRiot said:
going back to the array suggestion, could i not stick 1,2,3,4,5,6,7,8,9 in a 1d array, running a loop to cut off the first and last numbers, printing each time?

*cough*

Code:
String foo = "123456789";
for(int i = 0; i <= foo.length()/2; i++)
{
  System.out.println(foo.substring(i, foo.length()-i));
}

A string is essentially a 1D array insomuch as a String as stored as an immutable array of characters.
 
While your code only contains one loop, you'll probably discover that String.substring is implemented using a loop of its own.

You can write it with one loop, I think, but it's more challenging.
 
generelz said:
*cough*

Code:
String foo = "123456789";
for(int i = 0; i <= foo.length()/2; i++)
{
  System.out.println(foo.substring(i, foo.length()-i));
}

A string is essentially a 1D array insomuch as a String as stored as an immutable array of characters.

haha, sorry, im not too familiar with substring, but i see how i was overlooking it
:p
 
mikeblas said:
While your code only contains one loop, you'll probably discover that String.substring is implemented using a loop of its own.

You can write it with one loop, I think, but it's more challenging.

Actually substring in java is kind of nasty - it constructs a new string (which still points to the original string's character array) and just sets the lower/upper bound indicies to the previous string's lower/upper bound indicies plus/minus the first/last argument.
 
generelz said:
Actually substring in java is kind of nasty - it constructs a new string (which still points to the original string's character array) and just sets the lower/upper bound indicies to the previous string's lower/upper bound indicies plus/minus the first/last argument.
Interesting! And then they do copy-on-write? Or are strings immutable?

Even if substr doesn't have a loop to copy characters, println must, right?
 
mikeblas said:
Interesting! And then they do copy-on-write? Or are strings immutable?

yep, you got it. Strings are immutable. Substring can cause some memory usage issues though if you have a long string and get a substring - people don't realize that substring still points to the original char array.

mikeblas said:
Even if substr doesn't have a loop to copy characters, println must, right?

Not necessarily. It could simply do a memcpy from the char array to the block device...but fundamentally, there *is* probably a loop somewhere.
 
generelz said:
yep, you got it. Strings are immutable. Substring can cause some memory usage issues though if you have a long string and get a substring - people don't realize that substring still points to the original char array.
No wonder Java has such a poor reputation for performance!

generelz said:
Not necessarily. It could simply do a memcpy from the char array to the block device...but fundamentally, there *is* probably a loop somewhere.
How do you implement memcpy without a loop?
 
mikeblas said:
How do you implement memcpy without a loop?
You ... (pulls random important-sounding words out of a metaphorical hat) use a kernel that has vectorized it into SIMD instructions to feed to the MMU. Of course. :rolleyes:

It's only fair to note that he took the right precautions before mentioning memcpy: "but fundamentally, there *is* probably a loop somewhere.". I'll add that it's probably a very tight and well-optimized loop, though a loop nonetheless.

I'm guilty of optimizing an (explicit) loop away by doing the longest possible run once, storing the result, and memcpy-ing the interesting parts when I needed them. (Given that the content of the loop was just a simple "array=i", I doubt I gained much.)
 
HHunt said:
You ... (pulls random important-sounding words out of a metaphorical hat) use a kernel that has vectorized it into SIMD instructions to feed to the MMU. Of course. :rolleyes:
Huh?

Anyway, if memcpy() is called, why can't we be completely sure there's another loop?

Meanwhile, here's a version that uses one loop without substring:

Code:
int main()
{
	int nFirst = 1;
	int nLast = 9;
	int nCurrent = nFirst;

	while (nFirst <= nLast)
	{
		putchar('0' + nCurrent);

		if (++nCurrent > nLast)
		{
			nFirst++;
			nLast--;
			nCurrent = nFirst;
			putchar('\n');
		}
	}
	return 0;
}
 
mikeblas said:
I like to think I was inspired by this.
(Of course memcpy uses a loop. Even in the teoretical case of a hardware implementation there has to be a loop somewhere, unless the memory space is so small it can be done in one go. As I'm quite sure you've already concluded yourself. )

And by all means, good luck to the OP. :)
 
Does java have something similar to ostream.write()?

Code:
#include <iostream>

using namespace std;

int main() {
    const char* const foo("123456789");
    const char* iter = foo;
    for ( int i = 9; i > 0; i -= 2, *++iter ) {
        cout.write( iter, i );
        cout << "\n";
    }
}

or maybe something destructive like this:

Code:
#include <cstdio>

int main() {
    char* foo("123456789");
    for ( int i = 8; i > -1; --i, --i, *++foo ) {
        printf("%s\n", foo);
        foo[i] = 0;
    }
}

or

Code:
#include <cstdio>
#include <cstring>

int main() {
    char* foo("123456789");
    while ( *foo ) {
        printf("%s\n", foo );
        foo[ strlen( foo ) - 1 ] = 0;
        *++foo;
    }
}
 
Back
Top