1

In this exercise I had to write a method to print stars according to the integers of an array. I have finally got my code to pass, but I did not understand exactly why. The initial value of the integer star is 1, as 0 would not work properly. Why 1 and not 0? Can any of you give me the explanation? Thank u loads!

public class Printer {

    public static void main(String[] args) {
        // You can test the method here
        int[] array = {1,2,5,10};
        printArrayInStars(array);
    }

    public static void printArrayInStars(int[] array) {
        // Write some code in here
        for (int index = 0; index < array.length; index++) {
            int number = array[index];

            for (int star = 1; star <= number; star++) {
                System.out.print("*");

            }
            System.out.println("");
        }
    }
}
Turing85
  • 18,217
  • 7
  • 33
  • 58
  • Work through the loop by hand – Mad Physicist Aug 12 '20 at 17:59
  • change `for (int star = 1; star <= number; star++) {` to `for (int star = 0; star < number; star++) {`. As to why it works, i would recommen dreading [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Turing85 Aug 12 '20 at 17:59
  • There is nothing to do with the initial value of star. You are running the loop from `1 to <= number`. If you want to use `star = 0` then you need to run the loop til l `< number`. – BlackList96 Aug 12 '20 at 18:00

1 Answers1

0

it's normal. your loop should be something like :

for (int star = 0; star < number; star++)

or

for (int star = 1; star <= number; star++)
DEV
  • 1,607
  • 6
  • 19