i need a for loop to print out the numbers 1 2 4 8 16 32 64 128 256 512

any help?

Dani AI

Generated

The sequence asked for are powers of two. ’s multiply-each-iteration idea is the simplest; correctly pointed out that these are 2^n (Math.pow returns a double and needs casting). Below are compact, safe alternatives and a few cautions so the result behaves well beyond the tiny example shown in the thread.

A concise integer approach using bit shifts (no floating point, exact results):

for (int i = 0; i < 10; i++) {
    System.out.println(1 << i);
}

For larger ranges prefer a long to avoid early overflow:

for (int i = 0; i <= 62; i++) {
    System.out.println(1L << i);
}

Java 8+ stream style (readable, functional):

java.util.stream.IntStream.iterate(1, n -> n << 1)
    .limit(10)
    .forEach(System.out::println);

For very large exponents use BigInteger to avoid any fixed-width overflow:

import java.math.BigInteger;

BigInteger v = BigInteger.ONE;
for (int i = 0; i <= 100; i++) {
    System.out.println(v);
    v = v.shiftLeft(1);
}

Notes and cautions: Math.pow returns double (rounding and casting issues for big exponents). Signed int values stay positive only up to 2^30 (1 << 30); 1 << 31 flips the sign. Signed long stays positive up to 2^62 (1L << 62). Choose the method by required range and readability: simple multiply or shift for small ranges, BigInteger when exact big integers are needed.

Recommended Answers

All 4 Replies

got it, so simple after all

no thing but lol
before u post something work hard

OK friend, i am telling you the answer of this question. but it is so simple. Do little work before posting.

public static void main(String[] args) {
int initial = 1;
for(int i=0 ; i <= 10; i++){
System.out.println(initial);
initial = initial*2;
}
}

Hi;
May be the idea here is to understand how the binary numbers works;the numbers you print are all the power of 2.
you can do some thing lik:

public static void main(String[] args) {
        for (int i = 0; i <= 9; i++) {
            System.out.println(Math.pow(2, i));
        }
    }

if you did not want the digits after the point you can cast the result to int like this

public static void main(String[] args) {
        for (int i = 0; i <= 9; i++) {

            System.out.println((int)Math.pow(2, i));
        }
    }

or you can use the NumberFormat.

Hope it halps.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.