w3resource

Rust Program: Counting from 1 to 10

Rust Basic: Exercise-7 with Solution

Write a Rust program that counts from 1 to 10 using a loop and prints each number.

Sample Solution:

Rust Code:

fn main() {
    // Initialize a variable to start counting from
    let mut count = 1;

    // Start a loop that runs until count reaches 11
    while count <= 10 {
        // Print the current value of count
        println!("Count: {}", count);

        // Increment count by 1
        count += 1;
    }
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Count: 6
Count: 7
Count: 8
Count: 9
Count: 10

Explanation:

Here's a brief explanation of the above Rust code:

  • fn main() { ... }: This is the entry point of the program, where execution begins.
  • let mut count = 1;: This line declares a mutable variable named 'count' and initializes it with the value 1.
  • while count <= 10 { ... }: This line starts a "while" loop. The loop will continue executing as long as the condition count <= 10 evaluates to 'true'.
  • println!("Count: {}", count);: This line prints the current value of the 'count' variable using the println! macro. The {} is a placeholder for the value of 'count', which is provided as an argument to the println! macro.
  • count += 1;: This line increments the value of the 'count' variable by 1. After each iteration of the loop, the value of 'count' will be increased by 1.

Rust Code Editor:

Previous: Rust Program: Even or Odd number checker.
Next: Rust Program: Printing even numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.