Rust Program: Printing even numbers
Rust Basic: Exercise-8 with Solution
Write a Rust program that prints all even numbers from 1 to 20 using a while loop.
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 20
while count <= 20 {
// Check if the current number is even
if count % 2 == 0 {
// Print the current even number
println!("Even number: {}", count);
}
// Increment count by 1
count += 1;
}
}
Output:
Even number: 2 Even number: 4 Even number: 6 Even number: 8 Even number: 10 Even number: 12 Even number: 14 Even number: 16 Even number: 18 Even number: 20
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 <= 20 { ... }: This line starts a "while" loop. The loop will continue executing as long as the condition count <= 20 evaluates to 'true'.
- if count % 2 0 { ... }: This line starts an "if" statement. If the condition count % 2 0 evaluates to 'true', it means that the current value of 'count' is even.
- println!("Even number: {}", 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: Counting from 1 to 10.
Next: Rust Program: Printing array elements.
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-basic-exercise-8.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics