To print an Hourglass Pattern in Rust, we use nested loops. The outer loop controls the rows, and the inner loops control the spaces and stars (*) to form the pattern.
In this example,
print_hourglass
that takes the desired number of rows n
as a parameter.for
loops, where the outer loop runs from n
to 1 and the inner loops control the spaces and stars in each row.fn print_hourglass(n: usize) {
for i in (1..=n).rev() {
println!("{}{}", " ".repeat(n - i), "*".repeat(2 * i - 1));
}
for i in 2..=n {
println!("{}{}", " ".repeat(n - i), "*".repeat(2 * i - 1));
}
}
fn main() {
print_hourglass(5);
}
********* ******* ***** *** * *** ***** ******* *********
In this tutorial, we learned How to print Hour Glass Pattern in Rust language with well detailed examples.