Fallen_Hero
Fallen_Hero

Reputation: 11

Why does my printed staircase give a weird output instead of a regular staircase?

I'm kinda in a rush here so my problem here is this:

You have to make a staircase with n lines and k stars, with k increasing k times each time. (Also add a period on each line to start with)

The staircase should be right-situated like this:

.   *
.  **
. ***
.****

The function given is

printStairs(int n, int k) {
    
}

And so far my code is this:

void printStairs(int n, int k) {
    for (int i = 0; i < n; i += k) {
        print(".");
        
        for (int j = 0; j < n; j++) {
            
            if (j < n - i - k) {
                print(" ");
            } else {
                print("*");
            }
            
        }
        
        println();
    }
}

Can someone help?

Upvotes: 1

Views: 97

Answers (1)

apodidae
apodidae

Reputation: 2713

Solution with nested 'for' loops:

void buildStairs(int lines, int stars) {
  for (int x = lines; x > 0; x--) {
    print(".");
   // print(x);
    for (int y = 0; y < stars; y++) {
     // print(y);
      if (x - y < 2) {
        print("*");
      } else {
        print(" ");
      }   
    }
    println();
  }
}

Solution with nested 'while' loops:

void nestedWhile(int lines, int stars) {
  int i = lines;
  while (i > 0) {
    print(".");
    int j = 0;
    while (j < stars) {
      if (i - j < 2) {
        print("*");
      } else {
        print(" ");
      }
      j++;
    }
    println();
    i--;
  }
}

Nested 'for' loops converted to your lettering scheme:

void printStairs(int n, int k) {
  for (int i = n; i > 0; i--) {
    print(".");
    for (int j = 0; j < k; j++) {
      if (i-j < 2) {
        print("*");
      } else {
        print(" ");
      }
    }
    println();
  }
}

Upvotes: 1

Related Questions