Rust program to find the sum of all command-line arguments

Rust Example: Write a program to find the sum of all command-line arguments.
Submitted by Nidhi, on November 26, 2021

Problem Solution:

In this program, we will find the sum of all command-line arguments and print the result.

Program/Source Code:

The source code to find the sum of all command-line arguments is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to find the sum of 
// all command line arguments

fn main(){
	let args = std::env::args(); 
	let mut sum=0;
	let mut cnt=0;

	for arg in args {
		if cnt>0{
			sum = sum  + arg.parse::<i32>().unwrap();
		}
		cnt=1;
	}

	println!("Sum is: {}",sum);
}

Output:

Compile:
$ rustc main.rs

Execute:
$ ./main 10 15 20
Sum is: 45

Explanation:

In the main() function, we calculated the sum of all command-line arguments and printed the result.

Rust Miscellaneous Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.