Hello I'm begining to learn Java and I'm trying to convert from a While loop into a for loop. Sadly I'm just not quite grasping it...
I understand the loop is here

while (n * n > Math.pow(2,i))
	   {
	       i++;
	   }

but it's not quite as simple as changing the while to a for either...

import javax.swing.JOptionPane;
 public class Main_Class_WhileLoop {
	 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");
	   }
	 }

Hello I'm begining to learn Java and I'm trying to convert from a While loop into a for loop. Sadly I'm just not quite grasping it...
I understand the loop is here

while (n * n > Math.pow(2,i))
	   {
	       i++;
	   }

but it's not quite as simple as changing the while to a for either...

import javax.swing.JOptionPane;
 public class Main_Class_WhileLoop {
	 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");
	   }
	 }

Something like this would work.

for(int i=1;; i++)
{
    if(Math.pow(2,i) > n*n)
    {
System.out.println("2 raised to " + i
+ " is the first power of two greater than " + n + " squared");
   }
}

With your while loop, you have to be a little careful with equality, like if n=4, then 2^5 is bigger. But you would output 2^4 is bigger, because the reverse of < is >=, not >. So just be careful there.

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.