Reputation:
I want to print the pyramid pattern using word "Stream" by using for loop in Java. Please anyone can help me with this. I have printed pyramid with "*". I have also attached the program below:
Desired Result:
S
S t
S t r
S t r e
S t r e a
S t r e a m
What I have so far:
public class Pyramid
{
public static void main(String[] args)
{
System.out.println("-----Pyramid------");
int n = 5;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n - i; j++)
System.out.print(" ");
for (int k = 1; k <= 2 * i - 1; k++)
System.out.print("S");
System.out.print("\n");
}
}
}
Upvotes: 0
Views: 2791
Reputation: 1088
This should work with any word. As a hint I'd recommend to start loops with 0 instead of 1.
public static void main(String[] args) {
System.out.println("-----Pyramid------");
String word = "Stream";
int n = word.length();
for (int i = 0; i < n+2; i++) {
for (int j = 0; j <= n - i; j++)
System.out.print(" ");
for (int k = 0; k < i - 1; k++)
System.out.print(word.charAt(k) + " ");
System.out.print("\n");
}
}
Output:
-----Pyramid------
S
S t
S t r
S t r e
S t r e a
S t r e a m
Upvotes: 2
Reputation: 3419
You can use the charAt
method in order to extract from the word Stream the chars you need inside the loop to create the pyramid
For example:
"Stream".charAt(0);
Will print the char S
"Stream".charAt(3);
Will print the char e
.
More info here: String class reference
Upvotes: 2