---
title: "Implement a Rust program to calculate the sum of digits in a given number."  
description: "Implement a Rust program to calculate the sum of digits in a given number."  
author: "Utpal Vishwas"  
published: 2023-06-20  
updated: 2023-06-23  
canonical: https://www.mindstick.com/forum/158809/implement-a-rust-program-to-calculate-the-sum-of-digits-in-a-given-number  
category: "rust"  
tags: ["rust"]  
reading_time: 2 minutes  

---

# Implement a Rust program to calculate the sum of digits in a given number.

Implement a [Rust](https://www.mindstick.com/forum/160170/explain-rust-s-ownership-borrowing-and-lifetimes-system) [program to calculate](https://www.mindstick.com/forum/158772/write-a-python-program-to-calculate-the-sum-of-digits-in-a-given-number) the [sum of digits](https://www.mindstick.com/forum/157685/find-the-sum-of-digits-of-a-number-in-pl-sql) in a given number.

## Replies

### Reply by Aryan Kumar

Sure, here is a [Rust program](https://www.mindstick.com/forum/158800/create-a-rust-program-to-find-the-gcd-greatest-common-divisor-of-two-numbers) to calculate the [sum](https://www.mindstick.com/forum/159332/how-can-i-use-sum-in-linq) of digits in a given number:

Rust

```plaintext
fn sum_of_digits(number: i32) -> i32 {
    let mut sum = 0;
    let mut remainder = number;
    while remainder > 0 {
        let digit = remainder % 10;
        sum += digit;
        remainder = remainder / 10;
    }
    return sum;
}

fn main() {
    let number = 12345;
    let sum_of_digits = sum_of_digits(number);
    println!("The sum of digits in {} is {}", number, sum_of_digits);
}
```

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

```plaintext
rustc sum_of_digits.rs
```

Once the program is compiled, you can run it using the following command:

Code snippet

```plaintext
./sum_of_digits
```

This will print the following output to the console:

Code snippet

```plaintext
The sum of digits in 12345 is 15
```


---

Original Source: https://www.mindstick.com/forum/158809/implement-a-rust-program-to-calculate-the-sum-of-digits-in-a-given-number

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
