I want to change a while loop to a for loop but not sure how to do it. This is the loop.

[LIST=1]
[*]public static void main(String[] args) 
[*] { 
[*]   String input = JOptionPane.showInputDialog( 
[*]      "Please enter a number, 0 to quit:"); 
[*]   int n = Integer.parseInt(input); 
[*]   int i = 1; 
[*]   while (n * n > Math.pow(2,i)) 
[*]   { 
[*]       i++; 
[*]   }    
[*] System.out.println("2 raised to " + i 
[*]      + " is the first power of two greater than " + n + " squared"); 
[*]   } 
[*] }
[/LIST]

Recommended Answers

All 2 Replies

for (int i = 1; n * n > Math.pow(2,i); i++) {
...
}

Why don't you just take log base 2 of n and round up? No loop required...

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.