Menu
Coddy logo textTech

Number Pattern

Part of the Fundamentals section of Coddy's Rust journey — lesson 73 of 75.

When creating patterns like pyramids, we often need to create strings with repeated characters. In Rust, there are several ways to achieve this, but here's one of the most straightforward methods:

let str = "a".repeat(10);

str will hold "aaaaaaaaaa"

The repeat() method specifically requires a usize argument, not a regular integer type like i32.

usize is Rust's unsigned pointer-sized integer type - its size depends on your architecture (32 bits on 32-bit systems, 64 bits on 64-bit systems).

let count: usize = 5;
let repeated = "x".repeat(count);  // This works

If you have an i32 or another integer type, you'll need to convert it:

let num: i32 = 7;
let repeated = "y".repeat(num as usize);
// Convert with 'as usize'

This won't compile:

let repeated = "z".repeat(num);
// Error: expected usize, found i32
challenge icon

Challenge

Easy

Each test case has one input - an odd whole number.
Your task is to print n - pyramid using *, here are some examples:

1 - pyramid

*

5 - pyramid

*
***
*****

7 - pyramid

*
***
*****
*******

Input

  • odd integer n from user
  • 1 <= n < 1000

Tips

  • Try starting from the small triangles
  • Check the hint if you are stuck ;)

n represents the number of  * in the bottom row

Note: In Rust, functions that deal with the "size" or "length" of something (like .repeat()) require a type called usize instead of i32; you can treat usize as a normal whole number that is never negative.

Cheat sheet

To create strings with repeated characters in Rust, use the repeat() method:

let str = "a".repeat(10);

This creates "aaaaaaaaaa" (10 repetitions of "a").

The repeat() method only accepts usize (unsigned pointer-sized integer), not i32 or other integer types.

let count: usize = 5;
let repeated = "x".repeat(count); // Works

let num: i32 = 7;
let repeated = "y".repeat(num as usize); // Works

let repeated = "z".repeat(num);  // Error: expected usize, found i32

Try it yourself

use std::io;

fn main() {
    let mut input_n = String::new();
    io::stdin().read_line(&mut input_n).unwrap();
    let n: usize = input_n.trim().parse().unwrap();

    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals