Implement a Rust program to calculate the sum of digits in a given number.
Implement a Rust program to calculate the sum of digits in a given number.
393
20-Jun-2023
Aryan Kumar
23-Jun-2023Sure, here is a Rust program to calculate the sum of digits in a given number:
Rust
This function first defines a function called sum_of_digits that takes an i32 number as input and returns an i32. The function first initializes a variable called sum to 0. Then, the function iterates through the number, dividing the number by 10 and adding the remainder to the sum variable. Finally, the function returns the sum variable.
The main function of the program then calls the sum_of_digits function with the value 12345 as input. The result of the function call is then printed to the console.
To run the program, you can save it as a file called sum_of_digits.rs and then compile it using the following command:
Code snippet
Once the program is compiled, you can run it using the following command:
Code snippet
This will print the following output to the console:
Code snippet