programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

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

Justin Robbins
Ranch Hand
Posts: 121
2

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
You are doing integer Math:

5/2 = 2

2/2 = 1

1/2 = 0

0/2 = 0....

Les Morgan
Rancher
Posts: 779
19

Carey Brown
Saloon Keeper
Posts: 3329
46
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.