w3resource

Rust Program: Variable counter operations

Rust Basic: Exercise-3 with Solution

Write a Rust program that declares a mutable variable counter and initializes it with 0. Then increase it by 1 and decrease it by 1. At the end, print the variable value for each stage.

Sample Solution:

Rust Code:

fn main() {
    // Declare a mutable variable named 'counter' and initialize it with the value 0
    let mut counter = 0;

    // Print the initial value of the variable 'counter'
    println!("Initial value of counter: {}", counter);

    // Increase the value of 'counter' by 1
    counter += 1;

    // Print the value of 'counter' after increasing it
    println!("Value of counter after increasing: {}", counter);

    // Decrease the value of 'counter' by 1
    counter -= 1;

    // Print the value of 'counter' after decreasing it
    println!("Value of counter after decreasing: {}", counter);
}

Output:

Initial value of counter: 0
Value of counter after increasing: 1
Value of counter after decreasing: 0

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 counter = 0;: This line declares a mutable variable named counter and initializes it with the value 0.
  • println!("Initial value of counter: {}", counter);: This line prints the initial value of the variable counter using the println! macro. The {} is a placeholder for the value of counter, which is provided as an argument to the println! macro.
  • counter += 1;: This line increases the value of the variable counter by 1.
  • println!("Value of counter after increasing: {}", counter);: This line prints the value of the variable counter after increasing it.
  • counter -= 1;: This line decreases the value of the variable counter by 1.
  • println!("Value of counter after decreasing: {}", counter);: This line prints the value of the variable counter after decreasing it using the println! macro.

Rust Code Editor:

Previous: Rust Program: Adding two numbers.
Next: Rust Program: Integer-String conversion.

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.