To print a Hollow Square Pattern in Rust, you can use nested loops. The outer loop controls the rows, and the inner loop controls the columns. Conditions are used to determine whether to print stars or spaces for the pattern.
In this example,
print_hollow_square
that takes the side length n
as a parameter.for
loops, one for rows and one for columns, to iterate through each cell of the square.*
) for the border and spaces (
) for the inside.print_hollow_square
with the desired side length to print the pattern.fn print_hollow_square(n: i32) {
for i in 0..n {
let mut row = String::new();
for j in 0..n {
if i == 0 || i == n - 1 || j == 0 || j == n - 1 {
row.push('*');
} else {
row.push(' ');
}
}
println!("{}", row);
}
}
fn main() {
let side_length = 5;
print_hollow_square(side_length);
}
* * * * * * * * * * * * * * * *
In this tutorial, we learned How to print Hollow Square Pattern in Rust language with well detailed examples.