3 Replies - 688 Views - Last Post: 24 May 2011 - 12:26 AM Rate Topic: -----

#1 TOKYO64  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 18-October 10

I'm trying to see how many times this loop will work.

Posted 23 May 2011 - 10:33 PM

 public static void main (String [] args){
		int number = 2;
	    boolean done = false;
	    while (!done) {
	      number = number * 2;
	      if (number > 64) {
	        done = true;



Just trying to see how many times this will loop.

This post has been edited by macosxnerd101: 24 May 2011 - 12:38 PM
Reason for edit:: CODE TAGS!!! USE THEM!!!

Is This A Good Question/Topic? 0
  • +

Replies To: I'm trying to see how many times this loop will work.

#2 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,696
  • Joined: 19-March 11

Re: I'm trying to see how many times this loop will work.

Posted 23 May 2011 - 10:54 PM

Well, there's an easy empirical solution. Just put a counter in the loop and add one each time you go through. There's also an arithmetical solution, and a counting on your fingers solution.
Which solution do you prefer? Which answers do you come up with? Which answers do you trust, and why?
Was This Post Helpful? 1
  • +
  • -

#3 v0rtex  Icon User is offline

  • Caffeine: db "Never Enough!"
  • member icon

Reputation: 223
  • View blog
  • Posts: 773
  • Joined: 02-June 10

Re: I'm trying to see how many times this loop will work.

Posted 23 May 2011 - 11:28 PM

Well you could work it out in paper with a pencil, you have a number which starts @ 2, the looping of the while loop relies on the state of that integer as when it reaches over 64, you set the boolean value done to true and thus the loop can no longer meet its required condition and will not execute, as for how many times it will loop, you could simply work it out like so:
2*2 = 4, 4*2 = 8, 8*2 = 16, 16*2 = 32, 32*2 = 64, 64*2 = 128;
Therefore if you count how many multiplications occurred, the loop will run a total of
6 loops.


Hope this helps,
v0rtex

EDIT: You could also print out i and on every loop, increment i like so:
while (!done) {
number = number * 2;
i++;
System.out.println(i);
if (number > 64) {
done = true;
}
}


This post has been edited by v0rtex: 23 May 2011 - 11:28 PM

Was This Post Helpful? 2
  • +
  • -

#4 alpha_x  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 55
  • Joined: 03-May 11

Re: I'm trying to see how many times this loop will work.

Posted 24 May 2011 - 12:26 AM

Simply add a counter like vortex said and then that will display how many times the loop runs.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1