Trying to figure out how to make a pyramid that looks like this:
15 levels and screen width is 80. I can't figure out a pattern how to print it in the most useful way.
Trying to figure out how to make a pyramid that looks like this:
15 levels and screen width is 80. I can't figure out a pattern how to print it in the most useful way.
First of all
WhatHaveYouTried
first. Second, in order to achieve your goal, divide et impera, so lets get started!
char c = 'a'
and do c++
to get b
n
times increasing in each iteration, I've found a one-liner in this answerKnowing this :
public static void main(String[] args) throws Exception {
// get the char (point 1)
char c = 'a';
// iterate till 15 increasing 2 (31) - point 2)
for (int i = 1; i < 31; i +=2) {
// print spaces (point 3)
// NOTE 40 = 80/2 (screen size)
System.out.print(new String(new char[40-i/2]).replace("\0", " "));
// print body of pyramid (point 4)
System.out.println(new String(new char[i]).replace("\0", c +""));
// get next letter (point 1)
c++;
}
}
OUTPUT
a
bbb
ccccc
ddddddd
eeeeeeeee
fffffffffff
ggggggggggggg
hhhhhhhhhhhhhhh
iiiiiiiiiiiiiiiii
jjjjjjjjjjjjjjjjjjj
kkkkkkkkkkkkkkkkkkkkk
lllllllllllllllllllllll
mmmmmmmmmmmmmmmmmmmmmmmmm
nnnnnnnnnnnnnnnnnnnnnnnnnnn
ooooooooooooooooooooooooooooo