This article is aimed at giving a Rust implementation in printing of pyramid patterns.
First Pattern
Output:
*
**
***
****
*****
fn pyramid(n:i32) {
for row in 1..=n {
for _col in 1..=row {
print!("*");
}
println!("");
}
}
fn main() {
pyramid(5);
}
Second Pattern
Output:
*
**
***
****
*****
fn pyramid(n:i32) {
for row in (1..=n).rev() {
for col in 1..=n {
if col >= row {
print!("*");
} else {
print!(" ");
}
}
println!("");
}
}
fn main() {
pyramid(5);
}
Third Pattern
Output:
*****
****
***
**
*
****
***
**
*
fn pyramid(n:i32) {
for row in (1..=n).rev() {
for _col in 1..=row {
print!("*");
}
println!("");
}
}
fn main() {
pyramid(5);
}
Fourth Pattern
Output:
*****
****
***
**
*
****
***
**
*
fn pyramid(n:i32) {
let mut k = 2 * n - 2;
for row in (1..=n).rev() {
for _col in 1..=n-row {
print!(" ");
}
k = k - 2;
for _col in 1..=row {
print!("*");
}
println!("");
}
}
fn main() {
pyramid(5);
}
Fifth Pattern
Output:
*
***
*****
*******
***
*****
*******
fn pyramid(n:i32) {
let mut i:i32 = 0;
let mut j:i32 = 0;
let mut k:i32 = 0;
while i < n {
// for spacing
while k <= (n - i - 2) {
print!(" ");
k = k + 1;
}
k = 0;
// For Patter printing
while j < (2 * i - 1) {
print!("*");
j = j + 1;
}
j = 0;
i = i + 1;
println!(" ");
}
}
fn main() {
pyramid(5);
}
No comments:
Post a Comment