Search code examples
javawhile-loopincrementdecrement

Additional asterisks in my output


I'm aware that the increment operator = ++i, is shorthand for i = i +1
whereas the shorthand for decrement operator is --i (decrement operator being i = i -1).

In this case, I'm trying to print out a certain amount of asterisks for numStars and so I went with the increment operator (i = i + 1). I went with numPrinted = numPrinted + 1 to increment. Here is a brief glance of the code:

  numStars = 12;
  numPrinted = 1;

  while (numPrinted < numStars) {
     numStars = numStars * numPrinted;
     numPrinted = numPrinted + 1; //Went for increment since I'm assuming 
     additional asterisks will be shown

     System.out.print("*"); /* My output produces a total of 14 asterisks 
     whereas the expected output wants 12 asterisks */

  }

Seeing that the expected output is 12 and numStars = 12 already, was it necessary of me to put numStars = numStars * numPrinted? Because I feel that might be the reasons there's those two extra asterisks in my output rather than just 12 asterisks. Unless the extra two asterisks are there because of my decision to increment numPrinted?

Thank you in advance for the help and suggestions that will be made here.


Solution

  • Your loop will continue until numPrinted is more or equal to numStars.

    If you know that you want 12 loops, you should not be changing the value of numStars, only of numPrinted.

    Furthermore, numPrinted should not start at 1. This will result in 11 stars.

    The correct way to structure the loop, (should you wish to use a while loop instead of a for loop) is as follows:

      numStars = 12;
      numPrinted = 0;
    
      while (numPrinted < numStars) {
         numPrinted = numPrinted + 1; 
         System.out.print("*");
      }