Q:

Rust program to calculate the division without using division (/) operator

belongs to collection: Rust Basic Programs

0

In this program, we will calculate the division of two integer numbers without using the division (/) operator and print the result.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to calculate the division without using the '/' operator is given below. The given program is compiled and executed successfully.

// Rust program to calculate the 
// division without using '/' operator

fn division(mut num1:i32, mut num2:i32)->i32
{
   let mut negResult = false;
 
   if num1 < 0
   {
       num1 = -num1 ;
       if num2 < 0
       {
           num2 = - num2 ;
       }
       else
       {
           negResult = true;
       }
   }
   else if num2 < 0
   {
       num2 = - num2 ;
       negResult = true;
   }
 
   let mut quotient = 0;
   while num1 >= num2
   {
       num1 = num1 - num2 ;
       quotient=quotient+1 ;
   }
 
   if negResult == true
   {
        quotient = - quotient ;
   }
   return quotient ;
}

fn main() 
{
    let num1: i32  = 48;
    let num2: i32  = 4;
    let mut rs:i32 = division(num1,num2);

    println!("Division is: {}",rs);
}

Output:

Result is: 12

Explanation:

In the above program, we created two functions division() and main(). The division() function is used to calculate the division of two integer numbers without using the '/' operator and return the result to the calling function.

In the main() function, we created three integer variables num1num2rs that are initialized with 48, 4, 0 respectively. Then we called the division() function and assigned the result to the rs variable. After that, we printed the result.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Rust program to convert a float number into an int... >>
<< Rust program to create own Power function without ...