0

So recently a had an exam to make this simple program on java:

You enter a number, then the program needs to repeat a sequence based on the amount you entered, like this: if it was number 3 it should show 01-0011-000111, as you can see the numbers repeat in the same row, if it would be number 5 it should show: 01-0011-000111-00001111-0000011111 without the "-" symbol, I'm just putting it for you to understand better.The only thing I could do was this:

    Scanner lea = new Scanner(System.in);
    int number;
    int counter = 1;
    
    System.out.println("Enter a number");
    number = lea.nextInt();
    
    while(counter<=number){
        System.out.print("0");System.out.print("1");
        counter = counter + 1;
    }

thanks in advance!

St33v3n
  • 39
  • 2
  • 1
    try using multiple loops. Any logic that you do not understand, firstly try writing it would on paper. Just write down the steps. – Scary Wombat Aug 05 '22 at 02:36

2 Answers2

2

I have a feeling this is inefficient, but this is my idea:

You'd need to use 1 loop with 2 additional loops inside it. The outside loop will iterate N times (the amount the user specified), and the 2 loops inside will iterate the number of current iterations the outside loop has. One of them is for printing 0s and the other for printing 1s.

In code, it would look like so:

for(int i = 0; i < N; i++){
  for(int j = 0; j <= i; j++){
    System.out.print(0);
  }

  for(int j = 0; j <= i; j++){
    System.out.print(1);
  }

  if(i + 1 != N) System.out.print(" ");
}
parpar8090
  • 66
  • 9
  • a) User does not want `-` printed b) Code does not compile due to duplicate variables. - Apart from that all good? – Scary Wombat Aug 05 '22 at 02:45
  • @DawoodibnKareem Correct, it should've iterated `i` times because the first iteration only has one 0 and one 1, and the last iteration has N 0 and N 1, I will change it again. – parpar8090 Aug 05 '22 at 02:56
2

I'd rather use 1 for loop for this case with a formatted string using String.repeat

for (int i =0; i <= N; i++)
    System.out.print(String.format("%s%s ","0".repeat(i),"1".repeat(i)));
Melron
  • 569
  • 4
  • 10