Marco Roberts
Marco Roberts

Reputation: 205

Getting a new line printed before ouput?

I was solving a problem in a competitive site but my output is not matched with the test case output because a new line gets printed before my output. I am not able to detect which part of my code is printing it. Someone please help?

Problem

My solution:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    for(int i=n;i>=0;i--){
        int count=0;
        while(count<i){
            System.out.print(" ");
            count++;
        }
        while(count!=n){
            System.out.print("#");
            count++;
        }
        System.out.println();
    }
}

Test case o/p:

     #
    ##
   ###
  ####
 #####
######

My O/p:

  <NEWLINE> 
         #
        ##
       ###
      ####
     #####
    ######

Upvotes: 0

Views: 66

Answers (2)

Crabime
Crabime

Reputation: 684

for(int i=n;i>=1;i--){
        int count=0;
        while(count<i-1){
            System.out.print(" ");
            count++;
        }
        while(count!=n){
            System.out.print("#");
            count++;
       }
        System.out.println();
    }

just because the first time iterate you have already run six time so there are no more place to place "#" symbol,try this way.

Upvotes: 0

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26946

In the first for iteration you print only spaces and then a new line.

int n = in.nextInt();  
for(int i = n; i >= 0; i--) {
    int count=0;
    // At the first for iteration print exactly n spaces
    while(count < i){
        System.out.print(" ");
        count++;
    }
    // Here count equals i that equals n in the first for iteration
    // SO doesn't enter in the while
    while(count!=n){
        System.out.print("#");
        count++;
    }
    // And prints the new line
    System.out.println();
}

If you substitute SPACE with . the output should be:

......
.....#
....##
...###
..####
.#####
######

To solve your problem simply starts for loop from n - 1

Note in fact that you never need to print the line with only white spaces.

Upvotes: 2

Related Questions