• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why doesn't this for loop compute and how to convert from a for loop to a while loop?  RSS feed

 
Justin Robbins
Ranch Hand
Posts: 121
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why doesn't this go like:
5>1 [true]
val = 1
5/2 = 2.5

2.5>1 [true]
val = 2
2.5/2 = 1.25

1.25>1 [true]
val = 3;
1.25/2 = 0.625

Does this program fail because it cannot go from a double to an int? but isn't this going from an int to a double? getting confused on the widening and narrowing here.

Also, say I have the for loop:


I want to turn this into a while loop, is this the general procedure for converting a for loop to a while loop?

1. Take your starting points and place them up top [starting points/intilializations]
2. put your middle conditional statement of the for loop inside of the while loop condition [middle for loop condition]
3. then place any and all of the other conditional statements after the "while" [iteration/update statements]

so translated to a while loop would it look like this?:



Thank you. Any ideas on how to turn this into a do-while loop?
 
Les Morgan
Rancher
Posts: 779
19
C++ Java MySQL Database Netbeans IDE Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are doing integer Math:

5/2 = 2

2/2 = 1

1/2 = 0

0/2 = 0....
 
Les Morgan
Rancher
Posts: 779
19
C++ Java MySQL Database Netbeans IDE Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Carey Brown
Saloon Keeper
Posts: 3329
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Justin Robbins wrote:so translated to a while loop would it look like this?:

Actually, it looks more like this. 'i' gets modified at the end.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!