I'm currently beginning to program with Java. I tried to code the sequence in the title as an output in Java, but I'm stuck! I'm experimenting with the for function, any help is welcomed ;)
views:
821answers:
6Or did your teacher ask you to? Two nested for loops will do the trick.
Or in another way in another language (Ruby):
4.times {|n| print 10**(n+1)}
System.out.println("1 0 1 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0");
But seriously, folks, this is an untested first pass:
for(int i=1; i<100; i++){
System.out.print("1 ");
for(int j=0; j<i; j++){
System.out.print("0 ");
}
}
If you looking for basic info on how to get started, Google is your friend. For example, try googling for "for loop java" and you'll get a lot of good examples. Also, to learn basic things in any language, a google search for "<language> hello world" is very reliable.
You could store the number 10 in a variable, then in a loop print the number, multiply it by 10 (which appends a zero to its decimal representation), and repeat.
This is not really a question of fors but rather of very rudimentary algorithmic thinking. You have a sequence that consists of a "1", and then something else that grows over time", another "1", another something, etc. You can think of these as two different series that are interleaved.
Hence, overall structure would be something like:
while(... infinity?)
{
System.out.print("1");
doSomething();
}
Now the something clearly is correlated to the number of iterations ("stages") of the outer loop or the count of 1, so you need something like:
int stage=0;
while(...infinity?)
{
++stage;
System.out.print("1");
for(int i=0; i<stage; ++i) System.out.print("0");
}
If you know how many cycles you need to go through, use a for loop instead of a while, and increase stage through it.
for (int i = 2; i < 64; i <<= 1)
//System.out.print(Integer.toString(i, 2));
System.out.print(Integer.toString(i, 2).replaceAll("[01]", "$0 "));
Why two loops?
(converted from C#, pardon any syntax errors)
String s = "1 ";
for (int i = 0; i < 5; ++i)
{
s = s + "0 ";
System.out.print(s);
}
Self-critique:
- two for loops (like Michael Haren's solution) would negate the string copying
- a StringBuffer/StringBuilder would negate the string copying