Search code examples
c#for-loopconsole-applicationdivisionaccumulator

How can I divide two user inputs using only loops and using any operations is not allowed?


Console.Write("Input Value for A: ");

int a = int.Parse(Console.ReadLine());

Console.Write("Input Value for B: ");
int b = int.Parse(Console.ReadLine());

int acc = 0;
for (int i = a; a >= b; a--)
{
    acc += b;
}

Console.Write("The quotient is {0}", acc);
Console.ReadKey(true);

Solution

  • Well, this is a trick question, and therefore I immediately dislke it. The solution is the following:

    var quotient = 0;   
    for (var acc = b; acc <= a; acc += b, quotient += 1);
    Console.Write($"The quotient of {a} divided by {b} is {quotient}");
    

    The trick being that you are still using operations, but as a step in the loop itself and not as an explicit operation inside the loop body, which is probably the point of the excericse.

    UPDATE: This code only gives accurate results if a and b have the same sign.