Rust: Increment counter by specified amount
Rust Variables and Data Types: Exercise-3 with Solution
Write a Rust function that accepts a mutable reference to a counter variable and increments it by a specified amount.
Sample Solution:
Rust Code:
// Define a function named 'increment_counter' that takes a mutable reference to a counter variable and increments it by a specified amount
fn increment_counter(counter: &mut i32, amount: i32) {
*counter += amount; // Increment the counter by the specified amount
}
fn main() {
let mut counter = 0; // Define a mutable counter variable initialized with 0
let amount = 5; // Define the amount by which the counter should be incremented
increment_counter(&mut counter, amount); // Call the 'increment_counter' function with a mutable reference to the counter variable
println!("Counter after increment: {}", counter); // Print the value of the counter after incrementing it
}
Output:
Counter after increment: 5
Explanation:
Here's a brief explanation of the above Rust code:
- 'fn increment_counter(counter: &mut i32, amount: i32) { ... }': This is a function named 'increment_counter' that takes two parameters: a mutable reference to a counter variable ('counter') and the amount by which the counter should be incremented ('amount'). The counter variable is of type 'i32', a 32-bit integer.
- '*counter += amount;': This line increments the value of the 'counter' by adding the specified 'amount' to it. The '*' operator is used to dereference the mutable reference and modify the value it points to.
- 'fn main() { ... }': This is the program's entry point.
- 'let mut counter = 0;': This line defines a mutable counter variable named 'counter' and initializes it with the value '0'.
- 'let amount = 5;': This line defines the amount by which the counter should be incremented.
- 'increment_counter(&mut counter, amount);': This line calls the 'increment_counter' function with a mutable reference to the 'counter' variable and the specified 'amount'. The '&mut' operator creates a mutable reference to the 'counter' variable.
- 'println!("Counter after increment: {}", counter);': This line prints the value of the 'counter' variable after it has been incremented.
Rust Code Editor:
Previous: Rust: Calculate circumference from diameter and PI.
Next: Rust Weather Condition Checker: Check and set Boolean variable for Sunny weather.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/rust/basic/rust-variables-and-data-types-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics