Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Help with simple program  RSS feed

 
thomasaw hunt
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all, new here, I'm a recently retired guy who decided to learn some computer programming. I'm learning on my own and purchased a book called Java Concepts, Early Objects.

The problem I have is with a while loop. I believe I understand the concept and I know why my code is not working. I just don't know how to fix it.

The exercise is: Write a while loop that prints all squares less than n. For example if n = 100, print 0 1 4 9 16 25 36 49 64 81

Here is my code


my output is 0 1 4 9 16 25 36 49 64 81 100
The 100 is not wanted. I know that I get it because it is printed before the condition evaluates to false. How do I fix this. I know I'm missing something simple here.
 
Liutauras Vilda
Sheriff
Posts: 4928
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello thomasaw,

One possible solution in your current code would be to check inside the while loop after the multiplication is number less than n, if yes, print it (extra if within the while body).

Also, I'd suggest you to try find alternative solution for this problem, as this one probably is not the best one.
 
Knute Snortum
Sheriff
Posts: 4288
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

One way to do this is to change the condition in the while loop slightly. You don't want 100, so check for n - 1. Another way is to check the condition after the calculation. You do this with a do/while loop.

By the way, you should UseCodeTags (← click) when you post a program. It makes it easier to see the code. I've done it for you this time.

Have fun programming!
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Loops can be awkward; what you are doing there is checking the old value of squared before you start the loop.
By the way: combining variables with similar names like square and squared is a sure‑fire recipe for confusion.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!