Why is the do-while loop in my Java code printing '9'?

  • Context: Java 
  • Thread starter Thread starter Ghost Quartz
  • Start date Start date
  • Tags Tags
    Java Printing
Click For Summary

Discussion Overview

The discussion revolves around a Java programming issue concerning the behavior of a do-while loop and its output. Participants explore the reasons behind the output of '9' when using a do-while loop in conjunction with a while loop, focusing on debugging techniques and code structure.

Discussion Character

  • Technical explanation
  • Debugging techniques
  • Conceptual clarification
  • Debate/contested

Main Points Raised

  • One participant notes that the variable 'ad' needs to be reset before the do-while loop to avoid printing '9' as its initial value.
  • Another participant confirms that resetting 'ad' to 5 before the do-while loop resolves the issue.
  • Some participants suggest using print statements or a debugger to track variable values during execution for debugging purposes.
  • There is a suggestion that meaningful variable names can improve code readability, especially as complexity increases.
  • A debate arises regarding the necessity of the two loop constructs, with some arguing that the code could be streamlined with fewer loops.
  • Participants discuss the differences between while and do-while loops, emphasizing the condition testing order.
  • A participant expresses confusion about the loops, indicating a long absence from programming.
  • One participant shares a poetic comment, adding a light-hearted tone to the discussion.
  • Another participant shares a snippet of low-level code, contrasting it with the Java example and highlighting their experience with raw coding.

Areas of Agreement / Disagreement

Participants generally agree on the need to reset the variable 'ad' before the do-while loop. However, there is disagreement regarding the necessity of the two loops, with some believing it could be simplified while others defend the current structure. The discussion remains unresolved on the optimal approach to structuring the loops.

Contextual Notes

Some participants reference the potential for confusion between while and do-while loops, indicating a need for clarity in understanding their differences. There are also mentions of varying levels of programming experience among participants, which may influence their perspectives.

Ghost Quartz
Messages
8
Reaction score
4
TL;DR
Hi. I'm a beginner in java and was writing code that I expected to generate 15,16,17,18,5,6,7,8 as output, but I received 15,16,17 and 9. I don't understand why.
Java:
int bd= 15;
int ad= 5;

while(ad!=9){
        System.out.println(bd);
        ad++;
        bd++;
   }//output 15,16,17,18
do {
        System.out.println(ad);
        ad++;
   }while(ad<=9);//output 5,6,7,8

thanks for the help
 
Last edited by a moderator:
Technology news on Phys.org
you need to reset the ad value before the do loop as it is actually 9 at that point not 5.

So here's what happens the do loop prints the ad value which is 9 and then you add one to it and then the while condition says "hey the ad value is 10 hence ad>9 and so I'll stop".
 
  • Like
Likes   Reactions: Ghost Quartz
I wrote ad = 5; before do loop and it worked. Thank you very much!
 
  • Like
Likes   Reactions: jedishrfu
In general, to debug things like this it helps greatly to insert temporary print statements or to follow the execution in a debugger and look at important variable values at critical points.
 
  • Like
Likes   Reactions: Ghost Quartz, jim mcnamara, Vanadium 50 and 1 other person
FactChecker said:
In general, to debug things like this it helps greatly to insert temporary print statements or to follow the execution in a debugger and look at important variable values at critical points.
I will remind to do this for the next time. thanks:smile:
 
And while you're still a beginner, it would greatly help you to get in the habit of creating meaningful variable names. Your program is small enough that (ad and bd) are easy to read here, but it doesn't take much to reach a level of complexity where inscrutable var names are a real problem. Start that habit soon.

Also, maybe it's just me but I'm pretty sure you have a superfluous while in there.
 
  • Like
Likes   Reactions: Ghost Quartz
I know that. I learned while and do-while yesterday, so this program was just to synthesize the content. Thanks
 
  • Like
Likes   Reactions: jedishrfu
As a beginner, it is good to see that you are putting comments in that help to understand the code. Many do not. It is a skill that takes time to develop and it is good to start early. Don't be afraid to put more in. There are never(?) too many.
 
  • Like
  • Haha
Likes   Reactions: jedishrfu and DaveC426913
DaveC426913 said:
Also, maybe it's just me but I'm pretty sure you have a superfluous while in there.
Sadly, it's you. :-) The OP has a while loop for zero or more iterations and a do...while for one or more iterations. Of course, there are many ways to skin a cat so it's possible it could have been done in a more streamlined fashion with fewer loops.

Choose one or the other based on whether you need to execute the code at least once or not.

As an example, your program might use a do ... while when asking for input from the end-user and if the input is invalid or out of some program-defined bounds then loop around and ask the question(s) again, a one or more action.
 
  • #10
jedishrfu said:
Sadly, it's you. :-) The OP has a while loop for zero or more iterations and a do...while for one or more iterations. Of course, there are many ways to skin a cat so it's possible it could have been done in a more streamlined fashion with fewer loops.

Choose one or the other based on whether you need to execute the code at least once or not.

Yeah, no. I didn't the mean the While versus Do, I meant the two Whiles.

There's one at the start and one at the end.

Been decades since I programmed in Java and it's possible I'm mixing it up with a similar JavaScript structure.
 
  • #11
There are two loop constructs:
One while(...){...} to print 15,16,17,18
And another do{...}while(...) to print 5,6,7,8
 
  • Like
Likes   Reactions: jedishrfu and DaveC426913
  • #12
DaveC426913 said:
Yeah, no. I didn't the mean the While versus Do, I meant the two Whiles.

There's one at the start and one at the end.
I think you are confused about the difference between while loop versus a do... while loop. As @jedishrfu mentioned, the main difference is whether you want the condition tested before the iteration starts (while loop) or after an iteration (do...while loop).
DaveC426913 said:
Been decades since I programmed in Java and it's possible I'm mixing it up with a similar JavaScript structure.
The syntax of both types of loops is the same in Java and Javascript, as well as in C, C++, and C#.
 
  • Haha
Likes   Reactions: jedishrfu
  • #13
While and while conditions away
then do while you’re waiting
To do something today.

A little poetic nonsense for a beautiful sunny Austin Saturday.
 
  • #14
Mark44 said:
I think you are confused...
Yeah.

In my defense, it has been decades since I've been allowed to write in raw code, under pain of shunning. If you're not using a library that sits on a framework that sits on an engine, you are a leper.
Like forgetting your times tables because calculators are required now. :rolleyes:
 
  • #15
DaveC426913 said:
In my defense, it has been decades since I've been allowed to write in raw code
This is my idea of raw code (Intel x64 AVX2 - Advanced Vector Extensions with 256-bit regs):
C++:
ProcessRow:
     ; Read a row (8) of floats
     vmovdqu ymm1, ymmword ptr[r8]        ; Copy from source array to YMM1
     vrsqrtps ymm0, ymm1                  ; Put reciprocal square root values in YMM0
     vmovdqu ymmword ptr[rdx], ymm0       ; Copy results from YMM0 to destination array
     add r8, rsi                          ; Increment addresses in array by 8 bytes
     add rdx, rdi    
     loop ProcessRow

I posted the same snippet in another thread on fast reciprocal square roots - https://www.physicsforums.com/threads/fast-reciprocal-square-root-algorithm.1001061/post-6471417.
 

Similar threads

Replies
8
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 14 ·
Replies
14
Views
6K
  • · Replies 11 ·
Replies
11
Views
2K
  • · Replies 2 ·
Replies
2
Views
13K
  • · Replies 19 ·
Replies
19
Views
3K
  • · Replies 13 ·
Replies
13
Views
4K
Replies
1
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K