ADVERTISEMENT
ADVERTISEMENT

Rust program to calculate the sum of the digits of a given number using recursion

Rust | Sum of Digits Example: Given a number, we have to find the sum of its digits using the recursion function.
Submitted by Nidhi, on October 11, 2021

Problem Solution:

In this program, we will create a recursive function to calculate the sum of all digits of a given number using recursion and return the result to the calling function.

Program/Source Code:

The source code to calculate the sum of the digits of a given number using recursion is given below. The given program is compiled and executed successfully.

// Rust program to calculate the 
// sum of the digits of given number 
// using recursion

unsafe fn SumOfDigits(num:i32)->i32 {
	static mut sum:i32=0;
	if num > 0 {
		sum += (num % 10);
		SumOfDigits(num / 10);
	}
	return sum;
}

fn main() 
{
    unsafe{
        let res=SumOfDigits(1234);
        println!("Sum of digits are: {}",res);
    }
}

Output:

Sum of digits are: 10

Explanation:

In the above program, we created two functions SumOfDigits() and main(). The SumOfDigits() function is a recursive function, which is used to calculate the sum of the digits of the given number and return the result to the calling function.

In the main() function, we called SumOfDigits() function and printed the result.

Rust Functions Programs »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.