-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommand_Line_Args.rs
More file actions
71 lines (62 loc) · 2.3 KB
/
Command_Line_Args.rs
File metadata and controls
71 lines (62 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Silence some warnings so they don't distract from the exercise.
#![allow(dead_code, unused_mut, unused_variables)]
fn main() {
// This collects any command-line arguments into a vector of Strings.
// For example:
//
// cargo run apple banana
//
// ...produces the equivalent of
//
// vec!["apple".to_string(), "banana".to_string()]
let args: Vec<String> = std::env::args().skip(1).collect();
// This consumes the `args` vector to iterate through each String
for arg in args {
// 1a. Your task: handle the command-line arguments!
//
// - If arg is "sum", then call the sum() function
// - If arg is "double", then call the double() function
// - If arg is anything else, then call the count() function, passing "arg" to it.
if arg == "sum" {
sum();
}
else if arg == "double" {
double();
}
else{
count(arg)
}
// 1b. Now try passing "sum", "double" and "bananas" to the program by adding your argument
// after "cargo run". For example "cargo run sum"
}
}
fn sum() {
let mut sum = 0;
// 2. Use a "for loop" to iterate through integers from 7 to 23 *inclusive* using a range
// and add them all together (increment the `sum` variable). Hint: You should get 255
// Run it with `cargo run sum`
for i in 7..=23 {
sum += i;
}
println!("The sum is {}", sum);
}
fn double() {
let mut count = 0;
let mut x = 1;
// 3. Use a "while loop" to count how many times you can double the value of `x` (multiply `x`
// by 2) until `x` is larger than 500. Increment `count` each time through the loop. Run it
// with `cargo run double` Hint: The answer is 9 times.
while x < 500 {
x *= 2;
}
println!("You can double x {} times until x is larger than 500", count);
}
fn count(arg: String) {
// Challenge: Use an unconditional loop (`loop`) to print `arg` 8 times, and then break.
// You will need to count your loops, somehow. Run it with `cargo run bananas`
//
for i in 0..=7{
print!("{} ", arg); // Execute this line 8 times, and then break. `print!` doesn't add a newline.
}
println!(); // This will output just a newline at the end for cleanliness.
}